"""
/*
 * Copyright 2011 OpenWAF.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
 """
import sys

from Analyzer import  ExMethod, STypeDeclaration, SMethod, SClass
from Analyzer import SGlobal
from Analyzer import SEnum
from Analyzer import SPackage
from Compiler import WAFCompileError
from JavaLangAST import ArrayInitializer
from JavaLangAST import Class
from JavaLangAST import ClassOrInterfaceType
from JavaLangAST import Enum
from JavaLangAST import ExArguments
from JavaLangAST import ExArrayIndex
from JavaLangAST import ExCastExpression
from JavaLangAST import ExClass
from JavaLangAST import ExCreator
from JavaLangAST import ExDot
from JavaLangAST import ExIdentifier
from JavaLangAST import ExInnerCreator
from JavaLangAST import ExLiteral
from JavaLangAST import ExOperator
from JavaLangAST import ExParExpression
from JavaLangAST import ExPrimary
from JavaLangAST import ExPrimitiveType
from JavaLangAST import ExSuper
from JavaLangAST import ExThis
from JavaLangAST import ExType
from JavaLangAST import ExTypeArguments
from JavaLangAST import Literal
from JavaLangAST import LocalVariableDeclaration
from JavaLangAST import OprAdditive
from JavaLangAST import OprAssign
from JavaLangAST import OprBinary
from JavaLangAST import OprEquality
from JavaLangAST import OprInstanceOf
from JavaLangAST import OprLogical
from JavaLangAST import OprMultiplicative
from JavaLangAST import OprPostfix
from JavaLangAST import OprRelational
from JavaLangAST import OprShift
from JavaLangAST import OprTernary
from JavaLangAST import OprUnary
from JavaLangAST import PrimitiveType
from JavaLangAST import StmtAssert
from JavaLangAST import StmtBlock
from JavaLangAST import StmtBreak
from JavaLangAST import StmtContinue
from JavaLangAST import StmtDoWhile
from JavaLangAST import StmtExp
from JavaLangAST import StmtFor
from JavaLangAST import StmtForEach
from JavaLangAST import StmtIf
from JavaLangAST import StmtLocalVariableDeclaration
from JavaLangAST import StmtReturn
from JavaLangAST import StmtSwitch
from JavaLangAST import StmtThrow
from JavaLangAST import StmtTry
from JavaLangAST import StmtWhile
from JavaLangAST import Type
from JavaLangAST import TypeArgument
from ConfigReader import WAFConfig
from Java2js import SA
from Analyzer import SHelper


def some_method():
	raise Exception()

def check_instance(ob, classes):
	for cls in classes:
		if isinstance(ob, cls):
			return True
	return False

class SCS:#Java script writer
	currentClass = None
	currentMethod = None
	collect_locals = False 
	collect_locals_limit = -1
	locals_bag = None
	rc_counter=0
	s_temp_name=None
	direct_model_call=False
	s_model_call=None
	s_model_call2=None
	@staticmethod
	def getProxyCode():
		cs=SHelper.getImported("server.services.*")
		if cs==None:
			return None
		code=[]
		code.append("/** AUTO GENEREATED . DO NOT EDIT **/")
		code.append("package server.services;")
		code.append("")
		code.append("import java.io.IOException;")
		code.append("import java.io.PrintWriter;")
		code.append("import javax.servlet.ServletException;")
		code.append("import javax.servlet.http.HttpServlet;")
		code.append("import javax.servlet.http.HttpServletRequest;")
		code.append("import javax.servlet.http.HttpServletResponse;")
		code.append("import javax.xml.parsers.DocumentBuilder;")
		code.append("import javax.xml.parsers.DocumentBuilderFactory;")
		code.append("import java.net.URLDecoder;")
		code.append("import java.net.URLEncoder;")
		code.append("import org.w3c.dom.Document;")
		code.append("import org.w3c.dom.Element;")
		code.append("import org.w3c.dom.Node;")
		code.append("import org.w3c.dom.NodeList;")
		code.append("import com.openwaf.server.*;")
		code.append("public class WAFProxy extends HttpServlet {")
		code1=[]
		code1.append("@Override")
		code1.append("protected void doPost(HttpServletRequest request, HttpServletResponse response)")
		code1.append("throws ServletException, IOException {")
		code2=[]
		code2.append("response.setHeader(\"Cache-Control\", \"no-store, no-cache, must-revalidate\");")
		code2.append("response.addHeader(\"Cache-Control\", \"post-check=0, pre-check=0\");")
		code2.append("response.addHeader(\"Pragma\", \"no-cache\");")
		code2.append("PrintWriter out = response.getWriter();")
		code2.append("try{")
		code3=[]
		code3.append("DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();")
		code3.append("DocumentBuilder db = dbf.newDocumentBuilder();")
		code3.append("Document doc = db.parse(request.getInputStream());")
		code3.append("if (doc.getFirstChild().hasChildNodes()) {")
		code4=[]
		code4.append("NodeList nl = doc.getFirstChild().getChildNodes();")
		code4.append("int model_id = Integer.parseInt(nl.item(0).getTextContent());")
		code4.append("int method_id = Integer.parseInt(nl.item(1).getTextContent());")
		code4.append("nl = nl.item(2).getChildNodes();")
		
		for key in cs:
			cls=cs[key]
			code4.append("if(model_id=="+str(cls.getCLSID())+"){")
			code4.append(SCS.getProxyCodeForModel(cls))
			code4.append("}")
		code3.append(code4)
		code3.append("}")
		code2.append(code3)
		code2.append("}")
		code2.append("catch(Exception fex){}")
		code2.append("}")
		code1.append(code2)
		code1.append("}")
		code.append(code1)
		return code
	@staticmethod
	def getProxyCodeForModel(c):
		code=[]
		for m in c.methods:
			if m.isPublic()==False:continue
			if SCS.checkAsyncModelCall(m,c)==None:
				#if not isinstance(m,ExMethod):continue
				code.append("if(method_id=="+str(m.mid)+"){")			
				code.append(SCS.getProxyCodeForModelMethod(m,c))
				code.append("}")
		return code
	@staticmethod
	def checkAsyncModelCall(m,cls):
		count=0
		types=[]
		for p in m.pars:
			count+=1
			t=p.typ
			types.append(t)
			if SA.isBasicType(t) or SA.isStringType(t) or SA.isSingleDimentionBasicTypeArray(t):continue
			if t.coit.clazz==SGlobal.async_callback:
				if count!=len(m.pars):
					raise Exception("Async Calllback Parameter should be last in "+m.name)				
				mm=cls.getMethodWithThisAccess( m.name, types[:-1], True,None,None)
				if mm==None:
					raise Exception("Implemented method not found for "+m.name)
				return mm
			else:
				raise Exception( "Parameter type of index("+str(count)+") not supported in "+m.name)
		return None
	
			
			
			
			
			
	@staticmethod
	def getProxyCodeForModelMethod(m,cls):
		code=[]
		code.append("boolean __eo=false;")
		code.append("out.print(\"<?xml version=\\\"1.0\\\"?>\");")
		code.append("out.print(\"<response><data><![CDATA[\");")
		code.append("try{")
		code1=[]
		rline=None
		if m.rettype!=None:
			t=m.rettype
			if SA.isBasicType(t) or SA.isStringType(t):
				if SA.isStringType(t):
					code1.append("String r;")
					rline="out.print(URLEncoder.encode(r,\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.BOOLEAN:
					code1.append("boolean r;")
					rline="out.print(URLEncoder.encode(Boolean.toString(r),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.BYTE:
					code1.append("byte r;")
					rline="out.print(URLEncoder.encode(Byte.toString(r),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.CHAR:
					code1.append("char r;")
					rline="out.print(URLEncoder.encode(Integer.toString(Character.toString(r).codePointAt(0)),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.DOUBLE:
					code1.append("double r;")
					rline="out.print(URLEncoder.encode(Double.toString(r),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.FLOAT:
					code1.append("float r;")
					rline="out.print(URLEncoder.encode(Float.toString(r),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.INT:
					code1.append("int r;")
					rline="out.print(URLEncoder.encode(Integer.toString(r),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.LONG:
					code1.append("long r;")
					rline="out.print(URLEncoder.encode(Long.toString(r),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.SHORT:
					code1.append("short r;")
					rline="out.print(URLEncoder.encode(Short.toString(r),\"UTF-8\"));"
				else:
					print t.pm_type
					raise Exception("Unsupported type exception")
			elif SA.isSingleDimentionBasicTypeArray(t):
				t=t.coit.next
				if SA.isStringType(t):
					code1.append("String[] r;")
					rline="out.print(URLEncoder.encode(Utils.basicArrayToJSONArray(r).toString(),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.BOOLEAN:
					code1.append("boolean[] r;")
					rline="out.print(URLEncoder.encode(Utils.basicArrayToJSONArray(r).toString(),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.BYTE:
					code1.append("byte[] r;")
					rline="out.print(URLEncoder.encode(Utils.basicArrayToJSONArray(r).toString(),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.CHAR:
					code1.append("char[] r;")
					rline="out.print(URLEncoder.encode(Utils.basicArrayToJSONArray(r).toString(),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.DOUBLE:
					code1.append("double[] r;")
					rline="out.print(URLEncoder.encode(Utils.basicArrayToJSONArray(r).toString(),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.FLOAT:
					code1.append("float[] r;")
					rline="out.print(URLEncoder.encode(Utils.basicArrayToJSONArray(r).toString(),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.INT:
					code1.append("int[] r;")
					rline="out.print(URLEncoder.encode(Utils.basicArrayToJSONArray(r).toString(),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.LONG:
					code1.append("long[] r;")
					rline="out.print(URLEncoder.encode(Utils.basicArrayToJSONArray(r).toString(),\"UTF-8\"));"
				elif t.pm_type.value==PrimitiveType.SHORT:
					code1.append("short[] r;")
					rline="out.print(URLEncoder.encode(Utils.basicArrayToJSONArray(r).toString(),\"UTF-8\"));"
				else:
					print t.pm_type
					raise Exception("Unsupported type exception")
			elif SA.isSharedType(t):
				code1.append(t.coit.clazz.fullname+" r;")
				rline="out.print(URLEncoder.encode(r.toJSON().toString(),\"UTF-8\"));"
			elif SA.isArrayOfSharedType(t):
				code1.append(t.coit.next.coit.clazz.fullname+"[] r;")
				rline="out.print(URLEncoder.encode(Utils.sharedTypeArrayToJSONArray(r).toString(),\"UTF-8\"));"
			else:			
				raise Exception("Datatype not supported")
		count=0
		for p in m.pars:
			t=p.typ
			if SA.isBasicType(t) or SA.isStringType(t):
				if SA.isStringType(t):
					code1.append("String p"+str(count)+"=URLDecoder.decode(nl.item("+str(count)+").getTextContent(),\"UTF-8\");")
				elif t.pm_type.value==PrimitiveType.BOOLEAN:
					code1.append("boolean p"+str(count)+"=Boolean.parseBoolean(nl.item("+str(count)+").getTextContent());")
				elif t.pm_type.value==PrimitiveType.BYTE:
					code1.append("byte p"+str(count)+"=Byte.parseByte(nl.item("+str(count)+").getTextContent());")
				elif t.pm_type.value==PrimitiveType.CHAR:
					code1.append("char p"+str(count)+"=nl.item("+str(count)+").getTextContent().charAt(0);")
				elif t.pm_type.value==PrimitiveType.DOUBLE:
					code1.append("double p"+str(count)+"=Double.parseDouble(nl.item("+str(count)+").getTextContent());")
				elif t.pm_type.value==PrimitiveType.FLOAT:
					code1.append("float p"+str(count)+"==Float.parseFloat(nl.item("+str(count)+").getTextContent());")
				elif t.pm_type.value==PrimitiveType.INT:
					code1.append("int p"+str(count)+"=Integer.parseInt(nl.item("+str(count)+").getTextContent());")
				elif t.pm_type.value==PrimitiveType.LONG:
					code1.append("long p"+str(count)+"=Long.parseLong(nl.item("+str(count)+").getTextContent());")
				elif t.pm_type.value==PrimitiveType.SHORT:
					code1.append("short p"+str(count)+"=Short.parseShort(nl.item("+str(count)+").getTextContent());")
				else:
					raise Exception("Unsupported type exception")
			elif SA.isSingleDimentionBasicTypeArray(t):
				t=t.coit.next
				if SA.isStringType(t):
					code1.append("String[] p"+str(count)+"=Utils.JSONArrayToStringArray(URLDecoder.decode(nl.item("+str(count)+").getTextContent(),\"UTF-8\"));")
				elif t.pm_type.value==PrimitiveType.BOOLEAN:
					code1.append("boolean[] p"+str(count)+"=Utils.JSONArrayToBooleanArray(URLDecoder.decode(nl.item("+str(count)+").getTextContent(),\"UTF-8\"));")
				elif t.pm_type.value==PrimitiveType.BYTE:
					code1.append("byte[] p"+str(count)+"=Utils.JSONArrayToByteArray(URLDecoder.decode(nl.item("+str(count)+").getTextContent(),\"UTF-8\"));")
				elif t.pm_type.value==PrimitiveType.CHAR:
					code1.append("char[] p"+str(count)+"=Utils.JSONArrayToCharArray(URLDecoder.decode(nl.item("+str(count)+").getTextContent(),\"UTF-8\"));")
				elif t.pm_type.value==PrimitiveType.DOUBLE:
					code1.append("double[] p"+str(count)+"=Utils.JSONArrayToDoubleArray(URLDecoder.decode(nl.item("+str(count)+").getTextContent(),\"UTF-8\"));")
				elif t.pm_type.value==PrimitiveType.FLOAT:
					code1.append("float[] p"+str(count)+"=Utils.JSONArrayToFloatArray(URLDecoder.decode(nl.item("+str(count)+").getTextContent(),\"UTF-8\"));")
				elif t.pm_type.value==PrimitiveType.INT:
					code1.append("int[] p"+str(count)+"=Utils.JSONArrayToIntArray(URLDecoder.decode(nl.item("+str(count)+").getTextContent(),\"UTF-8\"));")
				elif t.pm_type.value==PrimitiveType.LONG:
					code1.append("long[] p"+str(count)+"=Utils.JSONArrayToLongArray(URLDecoder.decode(nl.item("+str(count)+").getTextContent(),\"UTF-8\"));")
				elif t.pm_type.value==PrimitiveType.SHORT:
					code1.append("short[] p"+str(count)+"=Utils.JSONArrayToShortArray(URLDecoder.decode(nl.item("+str(count)+").getTextContent(),\"UTF-8\"));")
				else:
					raise Exception("Unsupported type exception")
				
			else:
				print t
				print m.getName()
				if t.pm_type!=None:
					print t.pm_type.value
				else:
					print t.coit.fullname
				raise Exception("Datatype not supported")
			count+=1
		line=cls.getName()+"."+m.getName()+"("
		pars=[]
		count=0
		for p in m.pars:
			pars.append("p"+str(count))
			count+=1
		line+=",".join(pars)+");"
		if m.rettype==None:
			code1.append(line)
		else:
			code1.append("r="+line)
			code1.append(rline)		
		code.append(code1)
		code.append("}")
		code.append("catch(Exception e){")			
		code.append(["__eo=true;"])
		code.append(["try {"])
		code.append([["out.print(URLEncoder.encode(e.getMessage(), \"UTF-8\"));"]])
		code.append(["} catch (Exception _ex) {}"])
		code.append("}")
		code.append("out.print(\"]]></data>\");")
		code.append("if(__eo) {")
		code.append(["out.print(\"<success>0</success>\");"])
		code.append("} else {")
		code.append(["out.print(\"<success>1</success>\");"])
		code.append("}")
		code.append("out.print(\"</response>\");")
		code.append("return;");
		return code
		
	@staticmethod
	def checkMethod_Model(c,cls,jcode):
		m=SCS.checkAsyncModelCall(c, cls)
		if m!=None:
			return SCS.checkMethod_Model_async(c,cls,m,jcode)
		ro=WAFConfig.getWAFRootObjectName()
		code=[]
		count=0
		line="function("
		for p in c.pars:
			line+="p"+str(count)+","
			count+=1
		line+="g){"
		jcode.append(line)
		code.append("var d=\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><o><m>"+str(cls.getCLSID())+"</m><n>"+str(c.mid)+"</n><ps>\";")
		count=0
		for p in c.pars:
			if SA.isBasicType(p.typ) or SA.isStringType(p.typ):
				code.append("if(p"+str(count)+"==null)")
				code.append("d+=\"<p/>\";")
				code.append("else")
				code.append("d+=\"<p><![CDATA[\"+encodeURI(p"+str(count)+")+\"]]></p>\";")
			elif SA.isSingleDimentionBasicTypeArray(p.typ): 
				t=p.typ.coit.next
				ro=WAFConfig.getWAFRootObjectName()
				if SA.isStringType(t):
					code.append("if(p"+str(count)+"==null)")
					code.append("d+=\"<p/>\";")
					code.append("else")
					code.append("d+=\"<p><![CDATA[\"+encodeURI("+ro+".bf.s_s(p"+str(count)+"))+\"]]></p>\";")
				else:
					code.append("d+=\"<p><![CDATA[\"+"+ro+".bf.s_n(p"+str(count)+")+\"]]></p>\";")				
			else:
				raise Exception ("Non basic types not supported")
			count+=1
		code.append("d+=\"</ps></o>\"")
		code.append("var x="+ro+".bf.o();")
		code.append(ro+".bf.g[g].x=x;")
		#code.append("x.open(\"POST\",\""+WAFConfig.getProxyURL()+"\",true);")
		code.append("x.open(\"POST\",$app._proxy_url,true);")
		code.append("var s=this;")
		code.append("x.onreadystatechange=function(){s.gd_"+str(c.mid)+"(g);};")
		code.append("x.send(d);")
		jcode.append(code)
		jcode.append("}")
	@staticmethod
	def checkMethod_Model_async(c,cls,exm,jcode):
		ro=WAFConfig.getWAFRootObjectName()
		code=[]
		count=0
		line="function("
		ps=[]
		for p in c.pars:
			ps.append("p"+str(count))
			count+=1
		line+=",".join(ps)+"){"
		jcode.append(line)
		code.append("var d=\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><o><m>"+str(cls.getCLSID())+"</m><n>"+str(exm.method.mid)+"</n><ps>\";")
		count=0
		for p in c.pars:
			if count+1==len(c.pars):break
			if SA.isBasicType(p.typ) or SA.isStringType(p.typ):
				code.append("if(p"+str(count)+"==null)")
				code.append("d+=\"<p/>\";")
				code.append("else")
				code.append("d+=\"<p><![CDATA[\"+encodeURI(p"+str(count)+")+\"]]></p>\";")
			elif SA.isSingleDimentionBasicTypeArray(p.typ): 
				t=p.typ.coit.next
				ro=WAFConfig.getWAFRootObjectName()
				if SA.isStringType(t):
					code.append("if(p"+str(count)+"==null)")
					code.append("d+=\"<p/>\";")
					code.append("else")
					code.append("d+=\"<p><![CDATA[\"+encodeURI("+ro+".bf.s_s(p"+str(count)+"))+\"]]></p>\";")
				else:
					code.append("d+=\"<p><![CDATA[\"+"+ro+".bf.s_n(p"+str(count)+")+\"]]></p>\";")				
			else:
				raise Exception ("Non basic types not supported")
			count+=1
			
		code.append("d+=\"</ps></o>\"")
		code.append("var x="+ro+".bf.o();")
		code.append("x.open(\"POST\",\""+WAFConfig.getProxyURL()+"\",true);")
		code.append("var s=this;")
		code.append("x.onreadystatechange=function(){s.gd_"+str(c.mid)+"(x,p"+str(count)+");};")
		code.append("x.send(d);")
		jcode.append(code)
		jcode.append("}")
	@staticmethod
	def checkMethod_Model_gd(c,cls,jcode):
		
		m=SCS.checkAsyncModelCall(c, cls)
		if m!=None:
			return SCS.checkMethod_Model_gd_async(c,cls,jcode,m.rtype)
		ro=WAFConfig.getWAFRootObjectName()
		jcode.append("function(g){")
		code=[]
		code.append("var x="+ro+".bf.g[g].x;")
		code.append("if(x.readyState==4){")
		ccode=[]
		ccode.append("var r=x.responseText;")
		ccode.append("var d="+ro+".bf.x(r);")
		ccode.append("var ns="+ro+".bf.xn(d.lastChild);")
		ccode.append("var o="+ro+".bf.g[g].co;")
		ccode.append("var m="+ro+".bf.g[g].cb;")
		ccode.append("var ac="+ro+".bf.g[g].ac;")
		ccode.append("var i,a=[];")
		ccode.append("for(i=0;i<ac;i++){a.push(0);}")
		ccode.append("a.push(g);")
		ccode.append("a.push(0);")
		ccode.append("var t=ns[1].text ? ns[1].text : ns[1].textContent;")
		ccode.append("if(t==\"1\"){")
		ccode1=[]
		ccode1.append("r=ns[0].text ? ns[0].text : ns[0].textContent;")
		ccode1.append("r=decodeURIComponent(r.replace(/\\+/g,  \" \"));")
		if c.rettype!=None:
			if  SA.isBasicType(c.rettype) or SA.isStringType(c.rettype) or SA.isSingleDimentionBasicTypeArray(c.rettype):
				if SA.isSingleDimentionBasicTypeArray(c.rettype):
					ccode1.append("r=eval('(' + r +')');") 
				elif SA.isStringType(c.rettype):
					pass
				else:
					t=c.rettype.pm_type.value
					if t==PrimitiveType.CHAR:
						#ccode1.append("r=String.fromCharCode(r);")
						ccode1.append("r=parseInt(r);")
					elif t==PrimitiveType.BOOLEAN:				
						ccode1.append("r=(r==\"true\");")
					elif t in [PrimitiveType.BYTE,PrimitiveType.SHORT,PrimitiveType.LONG,PrimitiveType.INT]:
						ccode1.append("r=parseInt(r);")
					elif t in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
						ccode1.append("r=parseFloat(r);")
					else:
						raise Exception("Unhandled Basic Data Type")				
			elif SA.isSharedType(c.rettype):
				ccode1.append("r=eval('(' + r +')');")
				scls=c.rettype.coit.clazz
				cons=scls.getConstructor([],None)
				ccode1.append("if(r!=null){")
				ccode1.append("var so=(new " + scls.getPrototype() + "())." + cons.getJSName() + "();")
				SGlobal.initJSON()					
				if WAFConfig.isMinify():					
					ccode1.append("so._"+str(SGlobal.method_fromJSON.mid)+"(r);")
				else:
					ccode1.append("so."+SGlobal.method_fromJSON.name+"_"+str(SGlobal.method_fromJSON.mid)+"(r);")
				ccode1.append("r=so;")
				ccode1.append("}")			
			elif SA.isArrayOfSharedType(c.rettype):
				ccode1.append("r=eval('(' + r +')');")
				scls=c.rettype.coit.next.coit.clazz
				cons=scls.getConstructor([],None)
				ccode1.append("if(r!=null){")
				ccode1.append("var c,l=r.length;")
				ccode1.append("var k,oo=[];")
				ccode1.append("for(c=0;c<l;c++){")
				ccode1.append("k=(new " + scls.getPrototype() + "())." + cons.getJSName() + "();")
				SGlobal.initJSON()								
				if WAFConfig.isMinify():					
					ccode1.append("k._"+str(SGlobal.method_fromJSON.mid)+"(r[c]);")
				else:
					ccode1.append("k."+SGlobal.method_fromJSON.name+"_"+str(SGlobal.method_fromJSON.mid)+"(r[c]);")	
				ccode1.append("oo.push(k);")
				ccode1.append("}")
				ccode1.append("r=oo;")
				ccode1.append("}")
			else:
				raise Exception("Type not supported in model class")
			ccode1.append(ro+".bf.g[g].r=r")
		else:
			ccode1.append(ro+".bf.g[g].r=null")
		ccode1.append(ro+".bf.g[g].ex=null")		
		ccode.append(ccode1)
		ccode.append("}")
		ccode.append("else{")
		ccode1=[]
		ccode1.append("r=ns[0].text ? ns[0].text : ns[0].textContent;")
		ccode1.append("r=decodeURIComponent(r.replace(/\\+/g,  \" \"));")
		ccode1.append(ro+".bf.g[g].ex=r;")
		ccode1.append(ro+".bf.g[g].r=null")
		ccode.append(ccode1)
		ccode.append("}")
		ccode.append(ro+".bf.t(g,1);")		
		ccode.append("m.apply(o,a);")
		code.append(ccode)
		code.append("}")
		jcode.append(code)
		jcode.append("}")
	@staticmethod
	def checkMethod_Model_gd_async(c,cls,jcode,rettype):
		if SGlobal.async_on_success==None:
			for m in SGlobal.async_callback.methods:
				if m.name=="onSuccess":
					SGlobal.async_on_success=m
				if m.name=="onFailure":
					SGlobal.async_on_failure=m
				
			
			
		ro=WAFConfig.getWAFRootObjectName()
		jcode.append("function(x,cb){")
		code=[]
		code.append("if(x.readyState==4){")
		ccode=[]
		ccode.append("var r=x.responseText;")
		ccode.append("var d="+ro+".bf.x(r);")
		ccode.append("var ns="+ro+".bf.xn(d.lastChild);")
		ccode.append("var t=ns[1].text ? ns[1].text : ns[1].textContent;")
		ccode.append("if(t==\"1\"){")
		ccode1=[]
		ccode1.append("r=ns[0].text ? ns[0].text : ns[0].textContent;")
		ccode1.append("r=decodeURIComponent(r.replace(/\\+/g,  \" \"));")
		if rettype!=None:
			if  SA.isBasicType(rettype) or SA.isStringType(rettype):
				if SA.isStringType(rettype):
					pass
				else:
					t=rettype.pm_type.value
					if t==PrimitiveType.CHAR:
						#ccode1.append("r=String.fromCharCode(r);")
						ccode1.append("r=parseInt(r);")
					elif t==PrimitiveType.BOOLEAN:				
						ccode1.append("r=eval('('+r+')');")
					elif t in [PrimitiveType.BYTE,PrimitiveType.SHORT,PrimitiveType.LONG,PrimitiveType.INT]:
						ccode1.append("r=parseInt(r);")
					elif t in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
						ccode1.append("r=parseFloat(r);")
					else:
						raise Exception("Unhandled Basic Data Type")
			elif SA.isSharedType(rettype):
				ccode1.append("r=eval('(' + r +')');")
				scls=c.rettype.coit.clazz
				cons=scls.getConstructor([],None)
				ccode1.append("if(r!=null){")
				ccode1.append("var so=(new " + scls.getPrototype() + "())." + cons.getJSName() + "();")
				SGlobal.initJSON()								
				if WAFConfig.isMinify():					
					ccode1.append("so._"+str(SGlobal.method_fromJSON.mid)+"(r);")
				else:
					ccode1.append("so."+SGlobal.method_fromJSON.name+"_"+str(SGlobal.method_fromJSON.mid)+"(r);")
				ccode1.append("r=so;")
				ccode1.append("}")			
			elif SA.isArrayOfSharedType(rettype):
				ccode1.append("r=eval('(' + r +')');")
				scls=rettype.coit.next.coit.clazz
				cons=scls.getConstructor([],None)
				ccode1.append("if(r!=null){")
				ccode1.append("var c,l=r.length;")
				ccode1.append("var k,oo=[];")
				ccode1.append("for(c=0;c<l;c++){")
				ccode1.append("k=(new " + scls.getPrototype() + "())." + cons.getJSName() + "();")
				SGlobal.initJSON()								
				if WAFConfig.isMinify():					
					ccode1.append("k._"+str(SGlobal.method_fromJSON.mid)+"(r[c]);")
				else:
					ccode1.append("k."+SGlobal.method_fromJSON.name+"_"+str(SGlobal.method_fromJSON.mid)+"(r[c]);")				
				ccode1.append("oo.push(k);")
				ccode1.append("}")
				ccode1.append("r=oo;")
				ccode1.append("}")
			else:
				raise Exception("Type not supported in model class")
		if WAFConfig.isMinify():
			ccode1.append("cb._"+str(SGlobal.async_on_success.mid)+"(r);")		
		else:
			ccode1.append("cb.onSuccess_"+str(SGlobal.async_on_success.mid)+"(r);")
		ccode.append(ccode1)
		ccode.append("}")
		ccode.append("else{")
		ccode1=[]
		ccode1.append("r=ns[0].text ? ns[0].text : ns[0].textContent;")
		ccode1.append("r=decodeURIComponent(r.replace(/\\+/g,  \" \"));")
		if WAFConfig.isMinify():
			ccode1.append("cb._"+str(SGlobal.async_on_failure.mid)+"(r);")		
		else:
			ccode1.append("cb.onFailure_"+str(SGlobal.async_on_failure.mid)+"(r);")
		ccode.append(ccode1)
		ccode.append("}")
		code.append(ccode)
		code.append("}")
		jcode.append(code)
		jcode.append("}")
		
	
		
		
		
	@staticmethod	
	def checkMethod(c, cls, sym, i, jcode):
		old_class=SCS.currentClass
		rc_counter=SCS.rc_counter
		SCS.currentClass=cls
		m = c.method
		SCS.rc_counter=0
		outer_method=SA.currentMethod
		SCS.currentClass = SA.currentClass
		SA.currentMethod = c
		SCS.currentMethod=c
		sym.append({})
		i = i + 1
		line = "function("
		count = 0
		for p in c.pars:
			SHelper.processType(p.typ, SCS.currentClass, SCS.currentMethod)
			if count > 0:line += ","
			count += 1
			sym[i][p.name.data] = p			
			if m.block!=None and WAFConfig.isMinify():
				name=SA.getNextLocalSymbol(sym,"p")
				p.js_name=name
				sym[0][0][name]=1
				line += name
			else:
				sym[0][0][p.name.data]=1
				p.js_name=p.name.data
				line += p.name.data
		if len(c.pars)>0:
			line += ",_g,_f)"
		else:
			line +="_g,_f)"
		ro=WAFConfig.getWAFRootObjectName();
		if m.block != None:
			jcode.append(line)
			jcode.append("{")
			code=[]
			code.append("if(isNaN( parseInt( _g ))){_g=undefined;}")
			code.append("if(_g==undefined){_g="+ro+".bf.n();_f=0;}var _cf={};_cf.s="+ro+".bf.s(_g);if(_cf.s==-1){"+ro+".bf.i(_g);"+ro+".bf.t(_g,2);_cf.s=2;}")
			code.append("if(_cf.s==2){if(_f==0){"+ro+".bf.g[_g].cb=this."+c.getJSName()+";"+ro+".bf.g[_g].co=this;"+ro+".bf.g[_g].ac="+str(len(c.pars))+";}else{"+ro+".bf.f(_g,_f);}}")
			code.append("_cf.c="+ro+".bf.k(_g,_f);""")
			if len(c.pars)>0:
				code.append("if(_cf.s==1){")
				for p in c.pars:
					code.append(p.js_name+"="+ro+".bf.p(_g,_f,\""+p.js_name+"\");");
				code.append("}")
			jcode.append(code)
			#jcode.append("document.write('"+cls.fullname+"."+c.name+"<br/>');")
			code = []
			sym.append({})
			SCS.checkBlockStatements(m.block, sym, i+1, code)
			sym.pop()
			jcode.append(code)
			code.append("try{if(_f==0){ delete "+ro+".bf.g[_g];}else{ delete " +ro +".bf.g[_g].m[_f]; }}catch(e){}")
			jcode.append("}")
		else:
			some_method()
		sym.pop()
		SA.currentMethod=outer_method
		SCS.currentMethod=outer_method
		SCS.currentClass=old_class
		SCS.rc_counter=rc_counter
	@staticmethod
	def checkConstructor(c, cls, sym, i, jcode):
		old_class=SCS.currentClass
		SCS.currentClass=cls
		outer_method=SA.currentMethod
		SA.currentMethod = c
		SCS.currentMethod=c;
		m = c.method
		eci = None
		if m != None:
			eci = m.explconinv
		#TODO: check parameter declaration
		#TODO: find matching super class constructor
		sym.append({})
		i = i + 1

		line = "function("
		count = 0
		for p in c.pars:
			if count > 0:line += ","
			count += 1
			
			#SHelper.processType(p.typ,SCS.currentClass)
			sym[i][p.name.data] = p
			if WAFConfig.isMinify():
				name=SA.getNextLocalSymbol(sym,"p")
				p.js_name=name
				sym[0][0][name]=1
				line += name
			else:
				line += p.name.data
				sym[0][0][p.name.data]=1
				p.js_name=p.name.data
		if len(c.pars)>0:
			line += ",_g,_f)"
		else:
			line += "_g,_f)"
		#TODO:J handle constructor calling logic
		jcode.append(line)
		jcode.append("{")
		code=[]
		ro=WAFConfig.getWAFRootObjectName()
		code.append("if(isNaN( parseInt( _g ))){_g=undefined;}")
		code.append("if(_g==undefined){_g="+ro+".bf.n();_f=0;}var _cf={};_cf.s="+ro+".bf.s(_g);if(_cf.s==-1){"+ro+".bf.i(_g);"+ro+".bf.t(_g,2);_cf.s=2;}")
		code.append("if(_cf.s==2){if(_f==0){"+ro+".bf.g[_g].cb=this."+c.getJSName()+";"+ro+".bf.g[_g].co=this;"+ro+".bf.g[_g].ac="+str(len(c.pars))+";}else{"+ro+".bf.f(_g,_f);}}")
		code.append("_cf.c="+ro+".bf.k(_g,_f);""")
		if len(c.pars)>0:
			code.append("if(_cf.s==1){")
			for p in c.pars:
				code.append(p.js_name+"="+ro+".bf.p(_g,_f,\""+p.js_name+"\");");
			code.append("}")
		jcode.append(code)
		code = []
		line=None
		if eci != None:
			if eci.is_super == True:
				if (cls.exclass == None or len(cls.exclass) == 0) and eci != None:
					raise WAFCompileError(1006, cls.name)
				ex = cls.exclass[0]
				acode = []
				cc = ex.getConstructor(SCS.getExpressionListToTypeList(eci.arguments, sym, i, acode), SCS.currentClass)
				if cc == None:
					raise WAFCompileError("Super Constructor not found", None)
				line = "this." + cc.getJSName() + "(" + ",".join(acode)+ ");"
				#code.append(line)
			elif eci.is_this == True:
				acode = []
				cc = cls.getConstructor(SCS.getExpressionListToTypeList(eci.arguments, sym, i, acode), SCS.currentClass)
				if cc == None:
					raise WAFCompileError("Super Constructor not found", None)
				line = "this." + cc.getJSName() + "(" +",".join(acode) + ");"
				#code.append(line)
			else:				
				print some_method()
		else:
			if cls.exclass != None and len(cls.exclass) == 1:#calling default constructor automatically
				ex = cls.exclass[0]
				if cls.isClass() and cls.fullname != "java.lang.String":
					cons = ex.getConstructor([], SCS.currentClass)
					if cons == None:
						if len(ex.constructors) > 0:
							raise WAFCompileError(1005, ex.fullname)
					else:
						line = "this." + cons.getJSName() + "();"
						#code.append(line)
				elif cls.isEnum():
					args = [SGlobal.stringclass.mytype, SGlobal.basictypes[Literal.INT]]
					cons = ex.getConstructor(args, SCS.currentClass)
					v1=SA.getVariable("_n", sym, i)
					v2=SA.getVariable("_i", sym, i)
					line = "this." + cons.getJSName() + "("+v1.getJSName()+","+v2.getJSName()+");"
					#code.append(line)
				#else:
				#	some_method()
					
					
						
		if line!=None or cls.hasInstanceStaticBlocks():
			code.append("if(_cf.s==2){")
			if line!=None:
				code.append([line])
			if cls.hasInstanceStaticBlocks():
				code.append(["this."+cls.static_code_function_name+"();"])			
			code.append("}")
		vcode=SCS.checkVars(m.stmts, sym, i)
		jcode.append(vcode)
		if m != None:
			sym.append({})
			SCS.checkBlockStatements(m.stmts, sym, i+1, code)
			sym.pop()
		if cls.fullname != "java.lang.String":
			code.append("return this;")
		else:
			code[0] = "return " + code[0]
		jcode.append(code)
		code.append("try{if(_f==0){ delete "+ro+".bf.g[_g];}else{ delete " +ro +".bf.g[_g].m[_f]; }}catch(e){}")			
		jcode.append("}")
		sym.pop()
		SA.currentMethod= outer_method
		SCS.currentMethod=outer_method
		SCS.currentClass=old_class

	@staticmethod
	def checkStmt(st, sym, i, jcode):
		if check_instance(st, [StmtForEach, StmtLocalVariableDeclaration, StmtAssert, StmtBlock, StmtBreak, StmtIf, StmtFor, StmtWhile, StmtDoWhile, StmtSwitch, StmtReturn, StmtThrow, StmtContinue, StmtTry, StmtExp]):
			if isinstance(st, StmtAssert): 	return SA.checkStmtAssert(st, sym, i, jcode)
			if isinstance(st, StmtBlock):  	return SCS.checkBlock(st, sym, i, jcode)
			if isinstance(st, StmtBreak):  	return SA.checkStmtBreak(st, sym, i, jcode)
			if isinstance(st, StmtContinue):	   return SA.checkStmtContinue(st, sym, i, jcode)

			if isinstance(st, StmtFor):		return SCS.checkStmtFor(st, sym, i, jcode)
			if isinstance(st, StmtIf):	 	return SCS.checkStmtIf(st, sym, i, jcode)
			if isinstance(st, StmtLocalVariableDeclaration):	   return SCS.checkStmtLocalVariableDeclaration(st, sym, i, jcode)
			if isinstance(st, StmtReturn): 	return SCS.checkStmtReturn(st, sym, i, jcode)
			if isinstance(st, StmtSwitch): 	return SA.checkStmtSwitch(st, sym, i, jcode)
			if isinstance(st, StmtThrow):  	return SA.checkStmtThrow(st, sym, i, jcode)
			if isinstance(st, StmtTry):		return SCS.checkStmtTry(st, sym, i, jcode)
			if isinstance(st, StmtWhile):  	return SCS.checkStmtWhile(st, sym, i, jcode)
			if isinstance(st, StmtDoWhile):	return SA.checkStmtDoWhile(st, sym, i, jcode)
			if isinstance(st, StmtExp):	return SCS.checkStmtExp(st, sym, i, jcode)
			if isinstance(st, StmtForEach): return SA.checkStmtForEach(st, sym, i, jcode)
			print "Unexpected ", SA.ttos(st)
			some_method()
		else:
			print "KKK", SA.ttos(st)
			some_method()
	@staticmethod
	def checkStmtBlock(st, sym, i, jcode):#complete
		#TODO:to update index
		return SCS.checkBlock(st.block, sym, i, jcode)

	@staticmethod
	def checkStmtIf(st, sym, i, jcode):#complete
		code = []
		if st.par_ex_calls_model==True:
			####
			ro=WAFConfig.getWAFRootObjectName()
			rn=SA.getNextLocalSymbol(sym, "l");
			SCS.s_temp_name=rn;
			jcode.append("var "+rn+";")
			SCS.rc_counter+=1
			jcode.append("if(_cf.s==2){")#L:A
			jcode.append([ro+".bf.l(_g,_f,"+str(SCS.rc_counter)+");"])
			j=i
			while j >= 0:
				for vname in sym[j]:
					if j==0 and vname==0:continue
					vd=sym[j][vname]
					vname=vd.getJSName()
					jcode.append([ro+".bf.m(_g,_f,\""+vname+"\","+vname+");"])
				j -= 1
			code = []
			SCS.checkExpression(st.par.exp, sym, i, code)
			if SCS.direct_model_call==True:
				jcode.append([SCS.s_model_call+";"])
				jcode.append([ro+".bf.t(_g,0);"])
				#jcode.append("_cf.s=0;")
				jcode.append(["return;"])
			
				jcode.append("}")#L:A
				jcode.append("if(_cf.s==1 && _cf.c=="+str(SCS.rc_counter)+"){")#L:B
				jcode.append([rn+"="+ro+".bf.g[_g].r;"])
				#jcode.append([code[0] + ";"])
				jcode.append([ro+".bf.t(_g,2);"])
				jcode.append(["_cf.s=2;"])
				jcode.append("}");
			else:
				jcode.append([rn+"="+SCS.s_model_call])
				jcode.append(["if("+ro+".bf.s(_g)==0){return;}"])
				jcode.append("}")
				jcode.append("if(_cf.s==1 && _cf.c=="+str(SCS.rc_counter)+"){")#L:B
				jcode.append([rn+"="+SCS.s_model_call2])
				jcode.append(["if("+ro+".bf.s(_g)==0){return;}"])
				jcode.append(["_cf.s=2;"])
				jcode.append("}");
				#jcode.append(code[0] )
			####
		else:
			SCS.checkExpression(st.par.exp, sym, i, code)
		#SCS.checkParExpression(st.par, sym, i, code)		
		icode=[]
		SCS.checkStmt(st.stmt_if, sym, i, icode)
		jcode.append("if(_cf.s==1 && _cf.c<="+str(SCS.rc_counter)+"||(_cf.s==2&&" + code[0]+"))")
		for ic in icode:			
			jcode.append(ic)
		if st.stmt_else != None:
			jcode.append("else")
			SCS.checkStmt(st.stmt_else, sym, i, jcode)

	@staticmethod
	def checkStmtFor(st, sym, i, jcode):#complete
		sym.append({})
		
		if st.init != None:
			code = []
			SCS.assignLVD(st.init, sym, i+1)
			SCS.checkForInit(st.init, sym, i + 1, code)
			jcode.append("if(_cf.s==2){")			
			jcode.append([code[0]+";"])
			jcode.append("}")	
		fbcode=[]
		SCS.checkStmt(st.stmt, sym, i + 1, fbcode)
		line = "for(;(_cf.s==1&&_cf.c<="+str(SCS.rc_counter)+")"
		if st.cond != None:
			code = []
			SCS.checkExpression(st.cond, sym, i + 1, code)
			line += "||("+code[0]+")"
		line += ";"
		code = []
		SCS.checkExpressionList(st.exps, sym, i + 1, code)
		if len(code) > 0:
			line += code[0]
		line += ")"
		jcode.append(line)
		for l in fbcode:
			jcode.append(l)
		sym.pop()
		
	

	

	@staticmethod
	def checkForInit(st, sym, i, jcode):#complete
		if isinstance(st, LocalVariableDeclaration):
			return SCS.checkLocalVariableDeclaration(st, sym, i, jcode)
		return SCS.checkExpressionList(st, sym, i, jcode)

	@staticmethod
	def checkExpressionList(el, sym, i, jcode):#complete
		if len(jcode) == 0:jcode.append("")
		if el == None:return
		if not isinstance(el, list):
			print "Expecting list in CheckExpressionList"
			raise WAFCompileError(None, None)
		tcode = []
		for e in el:
			code = []
			SCS.checkExpression(e, sym, i, code)
			tcode.append(code[0])
		jcode[0] += ",".join(tcode)

	@staticmethod
	def checkStmtLocalVariableDeclaration(st, sym, i, jcode):
		if st.callsModel():
			##########
			ro=WAFConfig.getWAFRootObjectName()
			rn=SA.getNextLocalSymbol(sym, "l");
			SCS.s_temp_name=rn;
			jcode.append("var "+rn+";")
			SCS.rc_counter+=1
			jcode.append("if(_cf.s==2){")#L:A
			jcode.append([ro+".bf.l(_g,_f,"+str(SCS.rc_counter)+");"])
			j=i
			while j >= 0:
				for vname in sym[j]:
					if j==0 and vname==0:continue
					vd=sym[j][vname]
					vname=vd.getJSName()
					jcode.append([ro+".bf.m(_g,_f,\""+vname+"\","+vname+");"])
				j -= 1
			code = []
			r = SCS.checkStmtLocalVariableDeclaration2(st, sym, i, code)
			if SCS.direct_model_call==True:
				jcode.append([SCS.s_model_call+";"])
				jcode.append([ro+".bf.t(_g,0);"])
				#jcode.append("_cf.s=0;")
				jcode.append(["return;"])
			
				jcode.append("}")#L:A
				jcode.append("if(_cf.s==1 && _cf.c=="+str(SCS.rc_counter)+"){")#L:B
				jcode.append([rn+"="+ro+".bf.g[_g].r;"])
				jcode.append([code[0] + ";"])
				jcode.append([ro+".bf.t(_g,2);"])
				jcode.append(["_cf.s=2;"])
				jcode.append("}");
			else:
				jcode.append([rn+"="+SCS.s_model_call])
				jcode.append(["if("+ro+".bf.s(_g)==0){return;}"])
				jcode.append("}")
				jcode.append("if(_cf.s==1 && _cf.c=="+str(SCS.rc_counter)+"){")#L:B
				jcode.append([rn+"="+SCS.s_model_call2])
				jcode.append(["if("+ro+".bf.s(_g)==0){return;}"])
				jcode.append(["_cf.s=2;"])
				jcode.append("}");
				jcode.append(code[0] )
			return r

			##########
		else:
			return SCS.checkStmtLocalVariableDeclaration2(st, sym, i, jcode)
	@staticmethod
	def checkStmtLocalVariableDeclaration2(st,sym,i,jcode):
		code = []
		r = SCS.checkLocalVariableDeclaration(st.lvd, sym, i, code)
		if len(code)>0:
			jcode.append(code[0] + ";")
		return r
	@staticmethod
	def checkStmtWhile(st, sym, i, jcode):#complete
		code = []
		SCS.checkExpression(st.par.exp, sym, i, code)
		#SCS.checkParExpression(st.par, sym, i, code)		
		wcode=[]
		SCS.checkStmt(st.stmt, sym, i, wcode)
		jcode.append("while(_cf.s==1 && _cf.c<="+str(SCS.rc_counter)+"||(_cf.s==2&&" + code[0]+"))")
		for l in wcode:
			jcode.append(l)

	@staticmethod
	def checkStmtDoWhile(st, sym, i, jcode):#complete
		jcode.append("do")
		SCS.checkStmt(st.stmt, sym, i, jcode)
		line = "while"
		code = []
		SCS.checkParExpression(st.par, sym, i, code)
		line += code[0]
		jcode.append(line)

	@staticmethod
	def checkStmtSwitch(st, sym, i, jcode):#complete
		#TODO:J
		
		line = "switch"
		code = []
		is_enum = False
		t = SCS.checkParExpression(st.par, sym, i, code)
		if t.coit != None and t.coit.clazz != None:
				if isinstance(t.coit.clazz, SEnum):
					is_enum = True
		if is_enum == True:
			line += code[0][:-1] + ".ordinal)"
		else:	
			line += code[0]
		jcode.append(line)
		jcode.append("{")
		code = []
		for b in st.cases:
			SCS.checkSwitchBlock(b, sym, i, code, t)
		jcode.append(code)
		jcode.append("}")

	@staticmethod
	def checkSwitchBlock(sb, sym, i, jcode, t):#complete

		if sb.default == False:
			########
			#TODO:this can be optimized
			sym.append({})
			cls = None
			is_enum = False
			if t.coit != None and t.coit.clazz != None:
				if isinstance(t.coit.clazz, SEnum):
					cls = t.coit.clazz;
					is_enum = True	
					for name in cls.constants_hash:
						sym[i + 1][name] = cls
			
			#########
			code = []
			SCS.checkExpression(sb.exp, sym, i + 1, code)
			if is_enum:
				jcode.append("case " + t.coit.clazz.getPrototype() + ".prototype." + code[0] + ".ordinal:")
			else:
				jcode.append("case " + code[0] + ":")
			sym.pop()
		else:
			jcode.append("default:")
		for st in sb.stmts:
			SCS.checkBlockStatement(st, sym, i, jcode)

	@staticmethod
	def checkStmtReturn(st, sym, i, jcode):#complete
		ro=WAFConfig.getWAFRootObjectName()
		if st.exp != None:
			code = []
			t=SCS.checkExpression(st.exp, sym, i, code)
			code[0]=SA.applyJSTypeCast(t,SCS.currentMethod.rettype,code[0])
			code.append("try{if(_f==0){ delete "+ro+".bf.g[_g];}else{ delete " +ro +".bf.g[_g].m[_f]; }}catch(e){}")
			jcode.append("return " + code[0] + ";")
		else:
			code.append("try{if(_f==0){ delete "+ro+".bf.g[_g];}else{ delete " +ro +".bf.g[_g].m[_f]; }}catch(e){}")
			jcode.append("return;")


	@staticmethod
	def checkBlock(b, sym, i, jcode):#complete
		sym.append({})
		jcode.append("{")
		code = []
		SCS.checkBlockStatements(b.block, sym, i + 1, code)
		jcode.append(code)
		jcode.append("}")
		sym.pop()

	@staticmethod
	def checkBlockStatements(sts, sym, i, jcode):#complete
		code=SCS.checkVars(sts, sym, i)
		jcode+=code
		l=len(sts)
		count=0
		nbs=[]
		while True:
			if count==l:
				if len(nbs)==0:break
				code=[]
				for s in nbs:
					SA.checkBlockStatement(s, sym, i, code)
				jcode.append("if(_cf.s==2){")
				jcode.append(code)
				jcode.append("}")
				break
			st=sts[count]
			if not ( st.callsModel()==True or isinstance(st,StmtLocalVariableDeclaration) or (isinstance(st,StmtFor) and isinstance(st.init,LocalVariableDeclaration))):
				nbs.append(sts[count])
				count+=1
				continue
			if len(nbs)>0:
				code=[]
				for s in nbs:
					SA.checkBlockStatement(s, sym, i, code)
				jcode.append("if(_cf.s==2){")
				jcode.append(code)
				jcode.append("}")
				nbs=[]
			bcode=[]
			SCS.checkBlockStatement(st, sym, i, bcode)
			if st.callsModel():
				jcode.append("if(_cf.s==2||(_cf.s==1&&_cf.c<="+str(SCS.rc_counter)+")){")
				jcode.append(bcode)
				jcode.append("}")
			else:
				if len(bcode)>0:
					jcode.append("if(_cf.s==2){")
					jcode.append(bcode)
					jcode.append("}")
			count+=1

	@staticmethod
	def checkBlockStatement(st, sym, i, jcode):#complete
		#TODO:check this
		#if isinstance(st,StmtLocalVariableDeclaration):
		#	return SCS.checkLocalVariableDeclaration(st.lvd, sym, i, jcode)
		if isinstance(st, LocalVariableDeclaration):
			return SCS.checkLocalVariableDeclaration(st, sym, i, jcode)
		if check_instance(st, [Class, Enum]):
			#TODO:update this
			return ""
		SCS.checkStmt(st, sym, i, jcode)

	
	

	@staticmethod
	def checkStmtTry(st, sym, i, jcode):#inomplete
		jcode.append("try")
		SCS.checkBlock(st.tryblock, sym, i, jcode)
		jcode.append("catch(_ex){")
		jcode.append("var __ex=_ex;")
		if SGlobal.throwable_class==None:
			SGlobal.throwable_class=SHelper.getClassOnFullName("java.lang.Throwable")
			if SGlobal.throwable_class==None:
				raise Exception("Critical:class not found java.lang.Throwable")
		m=SGlobal.throwable_class.getMethodWithThisAccess("__valueOf",[SGlobal.objclass.mytype], True, None, None)
		code = []
		code.append("__ex=" + SGlobal.throwable_class.getPrototype()+".$."+ m.method.getJSName() + "(__ex);");
		add_else = False
		for ct in st.catches:
			sym.append({})
			sym[i + 1][ct.param.name.data] = ct.param
			if WAFConfig.isMinify():
				name=SA.getNextLocalSymbol(sym,"l")
				ct.param.js_name=name
				sym[0][0][name]=1
			else:
				sym[0][0][ct.param.name.data]=1
				ct.param.js_name=ct.param.name.data
			if add_else == True:
				code.append("else if(__ex instanceof " + ct.param.typ.coit.clazz.getPrototype() + ")");
			else:
				code.append("if(__ex instanceof " + ct.param.typ.coit.clazz.getPrototype() + ")");
			#SA.checkBlock(ct.block,sym,i+1,code)
			sym.append({})
			
			code.append("{")
			code.append(["var " + ct.param.getJSName() + "=__ex;"])
			cbcode = []
			SCS.checkBlockStatements(ct.block.block, sym, i + 1, cbcode)
			code.append(cbcode)
			code.append("}")
			sym.pop()

			sym.pop()
			add_else = True
		code.append("else throw __ex;")
		jcode.append(code)
		jcode.append("}")
		if st.finallyblock != None:
			jcode.append("finally")
			SCS.checkBlock(st.finallyblock, sym, i, jcode)
		
	@staticmethod
	def checkStmtExp(st, sym, i, jcode):#complete
		ro=WAFConfig.getWAFRootObjectName()
		rn=SA.getNextLocalSymbol(sym, "l");
		SCS.s_temp_name=rn;
		jcode.append("var "+rn+";")
		SCS.rc_counter+=1
		jcode.append("if(_cf.s==2){")#L:A
		jcode.append([ro+".bf.l(_g,_f,"+str(SCS.rc_counter)+");"])
		j=i
		while j >= 0:
			for vname in sym[j]:
				if j==0 and vname==0:continue
				vd=sym[j][vname]
				vname=vd.getJSName()
				jcode.append([ro+".bf.m(_g,_f,\""+vname+"\","+vname+");"])
			j -= 1
		code = []
		r = SCS.checkExpression(st.exp, sym, i, code)
		if SCS.direct_model_call==True:
			jcode.append([SCS.s_model_call+";"])
			jcode.append([ro+".bf.t(_g,0);"])
			#jcode.append("_cf.s=0;")
			jcode.append(["return;"])
		
			jcode.append("}")#L:A
			jcode.append("if(_cf.s==1 && _cf.c=="+str(SCS.rc_counter)+"){")#L:B
			jcode.append([rn+"="+ro+".bf.g[_g].r;"])
			jcode.append([code[0] + ";"])
			jcode.append([ro+".bf.t(_g,2);"])
			jcode.append(["_cf.s=2;"])
			jcode.append("}");
		else:
			jcode.append([rn+"="+SCS.s_model_call])
			jcode.append(["if("+ro+".bf.s(_g)==0){return;}"])
			jcode.append("}")
			jcode.append("if(_cf.s==1 && _cf.c=="+str(SCS.rc_counter)+"){")#L:B
			jcode.append([rn+"="+SCS.s_model_call2])
			jcode.append(["if("+ro+".bf.s(_g)==0){return;}"])
			jcode.append(["_cf.s=2;"])
			jcode.append("}");
			jcode.append(code[0] )
			
		return r

	@staticmethod
	def checkParExpression(e, sym, i, jcode):#complete
		code = []
		r = SCS.checkExpression(e.exp, sym, i, code)
		line = "(" + code[0] + ")"
		jcode.append(line)
		return r
	@staticmethod
	def checkVars(sts,sym,i):
		ro=WAFConfig.getWAFRootObjectName()
		for s in sts:
			if isinstance(s,StmtLocalVariableDeclaration):
				SCS.assignLVD(s.lvd,sym,i)
			elif isinstance(s,StmtFor) and isinstance(s.init,LocalVariableDeclaration):
				SCS.assignLVD(s.init,sym,i)
		code=[]
		vars=[]
		names=[]
		for v in sym[i]:
			if i==0 and v==0:continue
			names.append(v)
			vd=sym[i][v]
			v=vd.getJSName()
			vars.append(v)
			code.append(v+"="+ro+".bf.p(_g,_f,\""+v+"\");")
		for v in names:
			del sym[i][v]
		fcode=[]
		if len(vars)>0:
			fcode.append("var "+",".join(vars)+";")
		if len(code)>0:
			fcode.append("if(_cf.s==1){")
			fcode.append(code)
			fcode.append("}")
		return fcode
		
				
	@staticmethod
	def assignLVD(lvd, sym, i):#complete
		for vd  in lvd.vds:
			SCS.assignVD(vd, lvd.modifiers, sym, i)
	@staticmethod
	def assignVD(vd, modifiers, sym, i):#complete
		t = vd.typ
		SHelper.processType(t, SCS.currentClass, SCS.currentMethod)
		if vd.name.data == None:raise WAFCompileError(-1, "Critical Error")
		if sym[i].has_key(vd.name.data):
			print vd.name.lineno, vd.name.pos
			raise WAFCompileError(1001, vd.name)
		sym[i][vd.name.data] = vd#Var(line,vd.typ,vd.arraydim,modifiers)#TODO;what the hell is this
		if WAFConfig.isMinify():
			name=SA.getNextLocalSymbol(sym,"l")
			vd.js_name=name
			sym[0][0][name]=1
		else:
			sym[0][0][vd.name.data]=1
			vd.js_name=vd.name.data

	@staticmethod
	def checkLocalVariableDeclaration(lvd, sym, i, jcode):#complete
		line = ""
		count = 0
		l = len(lvd.vds)
		for vd  in lvd.vds:
			code = []
			SCS.checkVariableDeclarator(vd, lvd.modifiers, sym, i, code)
			if len(code)>0:
				line += code[0]
			count += 1
			if count == l: break
			if len(line)>0:
				line += ";"
		if len(line)>0:
			jcode.append(line)
		#TODO:add symbols here

	@staticmethod
	def checkVariableDeclarator(vd, modifiers, sym, i, jcode):#complete
		t = vd.typ
		sym[i][vd.name.data] = vd
		line=vd.getJSName()
		if vd.init != None:
			code = []
			t2=SCS.checkVariableInitializer(vd.init, sym, i, code)
			#################
			line = line + "=" + SCS.getVariableInitializerCode(t, t2, code[0], vd.init)
			jcode.append(line)
	@staticmethod
	def getVariableInitializerCode(t1,t2,code,init):
		if SHelper.matchType(t1, t2):
			return code
		if not isinstance(init,ArrayInitializer ):			
			_t2=SA.getTypeIfConstant(init.parts)
			if _t2!=None:
				t2=_t2
		if SA.isBasicType(t1) and SA.isBasicType(t2):
			d=SHelper.matchTypeAndGetDegree(t2, t1)
			if d==-1:
				raise WAFCompileError(1013, None)
			return code
		elif SA.isBasicType(t1) or SA.isBasicType(t2):
			if SA.isBasicType(t1):
				#unboxing
				if not SA.isWrapperClass(t2):raise "Can not assign value"
				u_t2=SA.fromWrapperClassToBasic(t2)
				d=SHelper.matchTypeAndGetDegree(u_t2,t1)
				if d==-1:
					raise WAFCompileError(1013, None)
				return code+".value"
			else:
				#TODO:make sure we have  wrapper her
				b_t2=SA.fromBasicToWrapperClass(t2)
				d=SHelper.matchTypeAndGetDegree(b_t2,t1)
				if d==-1:
					raise WAFCompileError(1013, None)
				return SA.boxIt(t2,code)
		else:#both are object
			d=SHelper.matchTypeAndGetDegree(t2,t1)
			if d!=-1:return code
			if SA.isWrapperClass(t1) and SA.isWrapperClass(t2):
				u_t1=SA.fromWrapperClassToBasic(t1)
				u_t2=SA.fromWrapperClassToBasic(t2)
				d=SHelper.matchTypeAndGetDegree(u_t2, u_t1)
				if d!=-1:
					return SA.boxIt(u_t2,code+".value")
		raise WAFCompileError(1013, None)



	@staticmethod
	def checkVariableInitializer(vi, sym, i, jcode):#complete
		if isinstance(vi, ArrayInitializer):
			return SCS.checkArrayInitializer(vi, sym, i, jcode)
		else:#expression
			return SCS.checkExpression(vi, sym, i, jcode)

	@staticmethod
	def checkDotDotExpression(curType, parts, pi, pcount, sym, i, jcode):
		#TODO:temp solution
		
		if len(jcode) == 0:jcode.append("")
		if SA.isDeclaration(curType):#for static
			
			method_type_args=None
			if isinstance(parts[pi], ExTypeArguments):
				method_type_args=[]				
				for arg in parts[pi].typeargs:
					SHelper.processType(arg, SCS.currentClass, SCS.currentMethod)
					ta = TypeArgument()
					ta.isany = False              		
					ta.typ = curType.mytype.mapAndConvertType(arg,None,SCS.currentMethod)
					method_type_args.append(ta)
				pi+=1
			if isinstance(parts[pi], ExIdentifier):
				name = parts[pi].name.data
				if (pi + 1) < pcount and isinstance(parts[pi + 1], ExArguments):
					
					args = parts[pi + 1].arguments
					code = []
					argstl = SCS.getExpressionListToTypeList(args, sym, i, code)
					_argstl = []
					for _arg in argstl: 
						_argstl.append(curType.mytype.mapAndConvertType(_arg,None,SCS.currentMethod))
					argstl = _argstl
					m = None
					
					m = curType.getMethodWithThisAccess(name, argstl, True,method_type_args, SCS.currentClass)
					if m == None:
						cc = SCS.getTypeDeclaration(curType)
						print name
						m = curType.getMethodWithThisAccess(name, argstl, True,method_type_args, SCS.currentClass)
						print cc.fullname
						print parts[pi].name.lineno
						raise WAFCompileError(1008, parts[pi].name)
					#if not m.isStatic():
					#		raise WAFCompileError(1014, parts[pi].name)
					SA.applyJSTypeCastForArguments(m, argstl, code)
					if curType.getDegreeWithThis(SGlobal.wafmodel)>=0:
						SCS.direct_model_call=True
						jcode[0]+=SCS.s_temp_name
						if len(code)>0: 
							SCS.s_model_call = curType.getPrototype()+".prototype."+ m.method.getJSName() + "(" + ",".join(code) + ",_g)"
						else:
							SCS.s_model_call = curType.getPrototype()+".prototype."+ m.method.getJSName() + "(_g)"
					else:
						jcode[0] += m.method.getJSName() + "(" + ",".join(code) + ")"
					if m.method.is_void == True:return None
					r = curType.mytype.mapAndConvertType(m.rtype,method_type_args,m.method)
					if pi + 2 == pcount:return r
					#TODO:here could be array
					if isinstance(parts[pi + 2], ExDot):
						jcode[0] += "."
						return SCS.checkDotDotExpression(r, parts, pi + 3, pcount, sym, i, jcode)
					if isinstance(parts[pi + 2], ExArrayIndex):						
						return SCS.checkDotDotExpression(r, parts, pi + 2, pcount, sym, i, jcode)
					raise WAFCompileError(0, "what is this in method")

				else:
					f = None
					f = curType.getFieldWithThisAccess(name, True, SCS.currentClass)
					if f == None:
						print name
						print curType.fullname
						print name, SCS.currentClass.fullname, SCS.currentMethod.name, curType.fullname
						raise WAFCompileError(1008, parts[pi].name)
					jcode[0] += f.field.getJSName()
					if pi + 1 == pcount:return f.type
					if isinstance(parts[pi + 1], ExDot):
						jcode[0] += "."
						return SCS.checkDotDotExpression(f.type, parts, pi + 2, pcount, sym, i, jcode)
					if isinstance(parts[pi + 1], ExArrayIndex):
						return SCS.checkDotDotExpression(f.type, parts, pi + 1, pcount, sym, i, jcode)
						"""	
						######
						code = []
						t = SCS.checkExpression(parts[pi + 1].exp, sym, i, code)
						if not SA.canBeArrayIndex(t):
							raise WAFCompileError("Can not evalute to positive integer")
						######
						jcode[0] += "[" + code[0] + "]"
						if pi + 2 == pcount:
							return SA.getTypeWithReducedArray(f.type)
						else:
							if isinstance(parts[pi + 2], ExDot):
								jcode[0] += "."
								return SCS.checkDotDotExpression(SA.getTypeWithReducedArray(f.type), parts, pi + 3, pcount, sym, i, jcode)
						"""
					raise WAFCompileError(0, "what is this")
			elif  isinstance(parts[pi], ExClass):
				jcode[0] += "_clz"
				if pi + 1 == pcount:
					return SHelper.getClassOnFullName("java.lang.Class").mytype
				if isinstance(parts[pi + 1], ExDot):
					jcode[0] += "."
					return SCS.checkDotDotExpression(curType, parts, pi + 2, pcount, sym, i, jcode)
					#TODO:Process
			elif isinstance(parts[pi], ExThis):
				jcode[0] += "this._pi"
				if pi + 1 == pcount:
					return curType.mytype
				if isinstance(parts[pi + 1], ExDot):
					jcode[0] += "."
					return SCS.checkDotDotExpression(curType.mytype, parts, pi + 2, pcount, sym, i, jcode)

			print "Not Handled 977/1851"
			print SA.toSParts(parts)
			some_method()




		SHelper.processType(curType, SCS.currentClass, SCS.currentMethod)
		method_type_args=None
		if isinstance(parts[pi], ExTypeArguments):
			method_type_args=[]				
			for arg in parts[pi].typeargs:
				SHelper.processType(arg, SCS.currentClass, SCS.currentMethod)
				ta = TypeArgument()
				ta.isany = False              		
				ta.typ =curType.mapAndConvertType(arg,None,SCS.currentMethod)
				method_type_args.append(ta)
			pi+=1
		if curType.coit != None:
			if isinstance(parts[pi], ExIdentifier):
				name = parts[pi].name.data
				if (pi + 1) < pcount and isinstance(parts[pi + 1], ExArguments):
					######### FOR IE 6
					#if accessing dom and compatibility is requested for IE 6/7
					if curType.coit.clazz.package=="com.openwaf.client.dom" and WAFConfig.isCompatibleWithIE67():
						args = parts[pi + 1].arguments
						code = []
						argstl = SCS.getExpressionListToTypeList(args, sym, i, code)
						#mapping not required
						cc=curType.coit.clazz
						m = curType.getMethodWithThisAccess(name, argstl, False,method_type_args, SCS.currentClass)
						if m==None:
							raise Exception("Method not found "+name)
						SA.applyJSTypeCastForArguments(m, argstl, code)
						if m.method.method.block == None and m.method.method.native_code == None:
							#can not minify this
							jcode[0]+=m.method.getJSName()+"("+",".join(code)+")"								
							rtype = m.rtype
							if pi + 2 == pcount:return rtype
							if isinstance(parts[pi + 2], ExDot):
								jcode[0] += "."
								return SCS.checkDotDotExpression(rtype, parts, pi + 3, pcount, sym, i, jcode)
							if isinstance(parts[pi + 2], ExArrayIndex):								
								return SCS.checkDotDotExpression(rtype, parts, pi + 2, pcount, sym, i, jcode)
							raise WAFCompileError(0, "what is this in method")
						else:
							if len(jcode[0])>0 and jcode[0][-1]==".":jcode[0]=jcode[0][:-1]
							line=None
							line=cc.getPrototype()+".prototype."+m.method.getJSName()+".call("
							if len(code)>0:
								jcode[0]=line+jcode[0]+","+",".join(code)+")"
							else:
								jcode[0]=line+jcode[0]+")"
							rtype = m.rtype
							if pi + 2 == pcount:return rtype
							if isinstance(parts[pi + 2], ExDot):
								jcode[0] += "."
								return SCS.checkDotDotExpression(rtype, parts, pi + 3, pcount, sym, i, jcode)
							if isinstance(parts[pi + 1], ExDot):
								return SCS.checkDotDotExpression(rtype, parts, pi + 1, pcount, sym, i, jcode)
							raise WAFCompileError(0, "what is this in method")
						
					######### FOR IE 6
					args = parts[pi + 1].arguments
					code = []
					argstl = SCS.getExpressionListToTypeList(args, sym, i, code)
					_argstl = []
					for _arg in argstl: 
						_argstl.append(curType.mapAndConvertType(_arg,None,SCS.currentMethod))
					argstl = _argstl
					m = curType.getMethodWithThisAccess(name, argstl, False,method_type_args, SCS.currentClass)
					if m == None:
						print SA.ttos(curType)
						print SCS.currentClass.fullname
						cc = SA.getTypeDeclaration(curType)
						print cc.fullname
						print parts[pi].name.lineno
						print name
						raise WAFCompileError(1008, parts[pi].name)
					SA.applyJSTypeCastForArguments2(curType.mappAllPars( m, method_type_args, SA.currentMethod), argstl, code)
					if m.method.isAbstract():
						if WAFConfig.isMinify() == False:
							jcode[0] +=  m.method.getName()+"_" + str(m.method.mid) + "(" + ",".join(code) + ")"						
						else:
							jcode[0] += "_" + str(m.method.mid) + "(" + ",".join(code) + ")"
					else:
						jcode[0] += m.method.getJSName() + "(" + ",".join(code) + ")"
					if m.method.is_void == True:return None
					rtype = curType.mapAndConvertType(m.rtype,method_type_args,m)	
					if pi + 2 == pcount:return rtype
					if isinstance(parts[pi + 2], ExDot):
						jcode[0] += "."
						return SCS.checkDotDotExpression(rtype, parts, pi + 3, pcount, sym, i, jcode)
					if isinstance(parts[pi + 2], ExArrayIndex):
						return SCS.checkDotDotExpression(rtype, parts, pi + 2, pcount, sym, i, jcode)
					raise WAFCompileError(0, "what is this in method")
				else:
					f = curType.getFieldWithThisAccess(name, False, SCS.currentClass)
					if f == None:raise WAFCompileError(1009, parts[pi].name)
					jcode[0] += f.field.getJSName()
					ftype = curType.mapAndConvertType(f.type,None,SCS.currentMethod)
					if pi + 1 == pcount:return ftype
					if isinstance(parts[pi + 1], ExDot):
						jcode[0] += "."
						return SCS.checkDotDotExpression(ftype, parts, pi + 2, pcount, sym, i, jcode)
					if isinstance(parts[pi + 1], ExArrayIndex):
						return SCS.checkDotDotExpression(ftype, parts, pi + 1, pcount, sym, i, jcode)
					raise WAFCompileError(0, "what is this")
			elif isinstance(parts[pi], ExArrayIndex):
				if  curType.coit == None or curType.coit.clazz != SGlobal.arrayclass:
					raise WAFCompileError(-1, "Not an array exception")
				p = parts[pi]
				code = []
				t = SCS.checkExpression(p.exp, sym, i, code)
				if not SA.canBeArrayIndex(t):
					raise WAFCompileError("Can not evalute to positive integer")
				jcode[0] += "[" + code[0] + "]"
				if pi + 1 == pcount:
					return SA.getTypeWithReducedArray(curType)
				else:
					if isinstance(parts[pi + 1], ExDot):
						jcode[0] += "."
						return SCS.checkDotDotExpression(SA.getTypeWithReducedArray(curType), parts, pi + 2, pcount, sym, i, jcode)
					if isinstance(parts[pi + 1], ExArrayIndex):
						return SCS.checkDotDotExpression(SA.getTypeWithReducedArray(curType), parts, pi + 1, pcount, sym, i, jcode)

				print "UnExpected:unexpected sequence"
				some_method()
			else:
				raise WAFCompileError("What is this")
		else:
			if isinstance(parts[pi], ExArrayIndex):
				if curType.coit == None or curType.coit.clazz != SGlobal.arrayclass:
					raise WAFCompileError(-1, "Not an array exception")
				p = parts[pi]
				code = []
				t = SCS.checkExpression(p.exp, sym, i, code)
				if not SA.canBeArrayIndex(t):
					raise WAFCompileError("Can not evalute to positive integer")
				jcode[0] += "[" + code[0] + "]"
				r=SA.getTypeWithReducedArray(curType)
				if pi + 1 == pcount:return r 
				if isinstance(parts[pi + 1], ExDot):
					jcode[0] += "."
					return SCS.checkDotDotExpression(r, parts, pi + 2, pcount, sym, i, jcode)
				if isinstance(parts[pi + 1], ExArrayIndex):
					return SCS.checkDotDotExpression(r, parts, pi + 1, pcount, sym, i, jcode)
				print "UnExpected:unexpected sequence"
				some_method()	
			else:
				raise WAFCompileError(-1, "What is this")


	@staticmethod
	def getExpressionListToTypeList(el, sym, i, jcode):#incomplete tested
		ts = []
		for e in el:
			code = []
			r = SCS.checkExpression(e, sym, i, code)
			if r == None:
				for p in el:
					print SA.toSParts(p.parts)
				print code
				raise WAFCompileError(0, "Invalid argument")#TODO:change this
			ts.append(r)
			jcode.append(code[0])
		return ts
	@staticmethod
	def checkExpression(e, sym, i, jcode):#incomplete
		if len(jcode) == 0:jcode.append("")
		return SCS.checkExpressionArray(e.parts, sym, i, jcode)

	@staticmethod
	def checkTuplePart(part, sym, i, jcode):
		if len(jcode) == 0:jcode.append("")
		if SA.isExpressionTuple(part):
			return SCS.checkExpressionTuple(part, sym, i, jcode)
		elif isinstance(part, ExPrimary):
			return SCS.checkExpressionArray(part.parts, sym, i, jcode)
		else:
			return SCS.checkExpressionArray(part, sym, i, jcode)
	@staticmethod
	def checkExpressionTuple(p, sym, i, jcode):

		l = len(p)
		if l == 2 and isinstance(p[0], ExOperator):
			o = p[0]
			jcode[0] += SA.checkOperator(p[0].value, sym, i)
			if not o.value >= OprUnary.INC and o.value <= OprUnary.TILDE:
				raise WAFCompileError(-1, "Wrong operator prefix")#TODO
			t = SCS.checkTuplePart(p[1], sym, i, jcode)
			if o.value == OprUnary.TILDE:
				if not (SA.isBasicNumericType(t) and t.pm_type.value in [ PrimitiveType.INT,PrimitiveType.LONG,PrimitiveType.BYTE,PrimitiveType.CHAR,PrimitiveType.SHORT]):
					raise WAFCompileError(1011, None)
				if t.pm_type.value in [PrimitiveType.BYTE,PrimitiveType.CHAR,PrimitiveType.SHORT]:
					return SGlobal.basictypes[PrimitiveType.INT]
				return t#int or long
			elif o.value == OprUnary.NOT:
				if not( SA.isBasicType(t)  and t.pm_type.value == PrimitiveType.BOOLEAN):
					raise WAFCompileError(1012, None)
				return t
			elif o.value in [OprUnary.DEC, OprUnary.INC]:
				if not SA.isBasicNumericType(t):
					raise WAFCompileError(1013, None)
				return t
			elif o.value in [OprUnary.NEGATIVE, OprUnary.POSITIVE]:
				if not SA.isBasicNumericType(t):
					raise WAFCompileError(1013, None)
				if t.pm_type.value in [PrimitiveType.BYTE,PrimitiveType.CHAR,PrimitiveType.SHORT]:
					return SGlobal.basictypes[PrimitiveType.INT]
				return t
			raise WAFCompileError(-1, "Critical Error 464")
		elif l == 2 and isinstance(p[1], ExOperator):
			o = p[1].value
			t = None
			t = SCS.checkTuplePart(p[0], sym, i, jcode)
			if not o in [OprPostfix.DEC, OprPostfix.INC]:
				raise WAFCompileError(-1, "Wrong Operaor postfix")#TODO
			if not SA.isBasicNumericType(t):
				raise WAFCompileError(1013, None)
			jcode[0] += SA.checkOperator(p[1].value, sym, i)
			return t
		elif l == 3 and isinstance(p[1], ExOperator):
			o = p[1].value
			lcode = []
			rcode = []
			t1 = SCS.checkTuplePart(p[0], sym, i, lcode)
			t2 = SCS.checkTuplePart(p[2], sym, i, rcode)
			if o in [OprMultiplicative.DIVIDE,OprMultiplicative.MULTIPY,OprMultiplicative.MOD,OprAdditive.MINUS,OprAdditive.PLUS,OprBinary.AND,OprBinary.OR,OprBinary.XOR]:
				if o==OprAdditive.PLUS:
					if SA.isStringType(t1) or SA.isStringType(t2):
						jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
						return SGlobal.stringclass.mytype
				if SA.isBasicNumericType(t1) and SA.isBasicNumericType(t2):
					dt1=t1.pm_type.value
					dt2=t2.pm_type.value
					if o in [OprBinary.AND,OprBinary.OR,OprBinary.XOR]:
						if dt1 in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
							raise "Shift can not be applied on float or double"
						if dt2 in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
							raise "Shift can not be applied on float or double"
					dt=max(dt1,dt2)
					jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
					if dt in [PrimitiveType.BYTE,PrimitiveType.CHAR,PrimitiveType.SHORT]:
						return SGlobal.basictypes[PrimitiveType.INT]
					return SGlobal.basictypes[dt]
				elif (SA.isBasicNumericType(t1) and SA.isWrapperClass(t2)) or (SA.isBasicNumericType(t2) and SA.isWrapperClass(t1)):
					if SA.isBasicNumericType(t1):
						if not SA.canUnbox(t2):raise "Can not unbox "
						ub_dt2=SA.fromWrapperClassToBasic(t2)
						dt1=t1
						if o in [OprBinary.AND,OprBinary.OR,OprBinary.XOR]:
							if dt1.pm_type.value in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
								raise "Shift can not be applied on float or double"
							if ub_dt2.pm_type.value in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
								raise "Shift can not be applied on float or double"
						jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]+".value"
						dt=max(dt1.pm_type.value,ub_dt2.pm_type.value)
						if dt in [PrimitiveType.BYTE,PrimitiveType.CHAR,PrimitiveType.SHORT]:
							return SGlobal.basictypes[PrimitiveType.INT]
						return SGlobal.basictypes[dt]
					else:
						if not SA.canUnbox(t1):raise "Can not unbox "
						ub_dt1=SA.fromWrapperClassToBasic(t1)
						dt2=t2
						if o in [OprBinary.AND,OprBinary.OR,OprBinary.XOR]:
							if dt2.pm_type.value in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
								raise "Shift can not be applied on float or double"
							if ub_dt1.pm_type.value in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
								raise "Shift can not be applied on float or double"
						dt=max(dt2.pm_type.value,ub_dt1.pm_type.value)
						jcode[0] += lcode[0]+".value" + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
						if dt in [PrimitiveType.BYTE,PrimitiveType.CHAR,PrimitiveType.SHORT]:
							return SGlobal.basictypes[PrimitiveType.INT]
						return SGlobal.basictypes[dt] 					
				elif SA.isWrapperClass(t1) or SA.isWrapperClass(t2):
					if not SA.canUnbox(t1):raise "Can not unbox"
					if not SA.canUnbox(t2):raise "Can not unbox"
					ub_dt1=SA.fromWrapperClassToBasic(t1)
					ub_dt2=SA.fromWrapperClassToBasic(t2)
					if o in [OprBinary.AND,OprBinary.OR,OprBinary.XOR]:
						if ub_dt1.pm_type.value in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
							raise "Shift can not be applied on float or double"
						if ub_dt2.pm_type.value in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
							raise "Shift can not be applied on float or double"
					dt=max(ub_dt1.pm_type.value,ub_dt2.pm_type.value)
					jcode[0] += lcode[0]+".value" + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]+".value"
					if dt in [PrimitiveType.BYTE,PrimitiveType.CHAR,PrimitiveType.SHORT]:
						return SGlobal.basictypes[PrimitiveType.INT]
					return SGlobal.basictypes[dt]
				raise WAFCompileError(1013, None)

			elif o in [OprShift.LEFT_SHIFT,OprShift.RIGHT_SHIFT,OprShift.RIGHT_RIGHT_SHIFT]:
				jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
				if (not SA.isBasicNumericType(t1)) or ( not SA.isBasicNumericType(t2)):
					raise WAFCompileError(1013, None)
				dt1=t1.pm_type.value
				dt2=t2.pm_type.value
				if dt1 in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
					raise "Shift can not be applied on float or double"
				if dt2 in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
					raise "Shift can not be applied on float or double"
				dt=dt1#NOTE:int shift left operand is important
				if dt in [PrimitiveType.BYTE,PrimitiveType.CHAR,PrimitiveType.SHORT]:
					return SGlobal.basictypes[PrimitiveType.INT]
				return SGlobal.basictypes[dt]
			elif o == OprInstanceOf.INSTANCEOF:
				#TODO:reducet this
				#TODO:optimize this
				tc=SHelper.getClassOnFullName("com.openwaf.core.framework.TypeCast")
				m=tc.getMethodWithThisAccess("instanceOf", [SGlobal.objclass.mytype,SGlobal.objclass.mytype],True, None,None)
				jcode[0] += tc.getPrototype()+".$."+m.method.getJSName() +"(" + lcode[0] + "," + rcode[0] + ")"
				return SGlobal.basictypes[PrimitiveType.BOOLEAN]
				
			elif o in [ OprEquality.ET, OprEquality.NET, OprLogical.AND, OprLogical.OR, OprRelational.GT, OprRelational.GTE, OprRelational.LT, OprRelational.LTE]:
				if SA.isBasicType(t1) and SA.isBasicType(t2):
					jcode[0] += lcode[0] + SA.checkOperator(p[1].value, sym, i) + rcode[0]
				elif SA.isBasicType(t1) or SA.isBasicType(t2):
					if SA.isBasicType(t1):
						if SA.isWrapperClass(t2):
							jcode[0] += lcode[0] + SA.checkOperator(p[1].value, sym, i) + rcode[0]+".value"
						else:
							raise "Can not compare these data types"
					else:
						if SA.isWrapperClass(t1):
							jcode[0] += lcode[0]+".value" + SA.checkOperator(p[1].value, sym, i) + rcode[0]
						else:
							raise "Can not compare these data types"
				else:#both are object
					if SA.isWrapperClass(t1) and SA.isWrapperClass(t2):
						jcode[0] += lcode[0]+".value" + SA.checkOperator(p[1].value, sym, i) + rcode[0]+".value"
					else:
						#nothing much we can do here
						jcode[0] += lcode[0] + SA.checkOperator(p[1].value, sym, i) + rcode[0]
					
				
				return SGlobal.basictypes[PrimitiveType.BOOLEAN]
			elif o in [ OprAssign.NORMAL, OprAssign.PLUS,OprAssign.MINUS,OprAssign.MULTIPLY,OprAssign.DIVIDE,OprAssign.MOD,OprAssign.AND,OprAssign.XOR,OprAssign.OR,OprAssign.LEFT_SHIFT,OprAssign.RIGHT_SHIFT,OprAssign.RIGHT_RIGHT_SHIFT]:
				if o==OprAssign.NORMAL or o==OprAssign.PLUS:
					if SHelper.matchType(t1, t2):
						jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
						return t1
					if o==OprAssign.NORMAL:
						_t2=SA.getTypeIfConstant(p[2])
						if _t2!=None:
							t2=_t2
					if SA.isBasicType(t1) and SA.isBasicType(t2):
						d=SHelper.matchTypeAndGetDegree(t2, t1)
						if d==-1:
							raise WAFCompileError(1013, None)
						jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
						return t1
					elif SA.isBasicType(t1) or SA.isBasicType(t2):
						if SA.isBasicType(t1):
							#unboxing
							u_t2=SA.fromWrapperClassToBasic(t2)
							d=SHelper.matchTypeAndGetDegree(u_t2,t1)
							if d==-1:
								raise WAFCompileError(1013, None)
							jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]+".value"
							return t1
						else:
							#TODO:make sure we have  wrapper her
							b_t2=SA.fromBasicToWrapperClass(t2)
							d=SHelper.matchTypeAndGetDegree(b_t2,t1)
							if d==-1:
								raise WAFCompileError(1013, None)
							jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + SA.boxIt(t2,rcode[0])
							return SA.fromWrapperClassToBasic(t1)
					else:#both are object
						
						d=SHelper.matchTypeAndGetDegree(t2,t1)
						if d!=-1:
							jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
							return t1	
						if SA.isWrapperClass(t1) and SA.isWrapperClass(t2):
							u_t1=SA.fromWrapperClassToBasic(t1)
							u_t2=SA.fromWrapperClassToBasic(t2)
							d=SHelper.matchTypeAndGetDegree(u_t2, u_t1)
							if d!=-1:
								jcode[0] += lcode[0]+".value" + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]+".value"
								return t1
						raise WAFCompileError(1013, None)
				if (not SA.isBasicNumericType(t1)) or ( not SA.isBasicNumericType(t2)):
					raise WAFCompileError(1013, None)
				dt1=t1.pm_type.value
				dt2=t2.pm_type.value 
				if o in [OprAssign.MINUS,OprAssign.MULTIPLY,OprAssign.DIVIDE,OprAssign.MOD]:
					jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
					return SGlobal.basictypes[dt1]
				elif o in [OprAssign.AND ,OprAssign.OR,OprAssign.XOR,OprAssign.LEFT_SHIFT,OprAssign.RIGHT_SHIFT,OprAssign.RIGHT_RIGHT_SHIFT]:
					jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
					if dt1 in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
						raise "Shift can not be applied on float or double"
					if dt2 in [PrimitiveType.FLOAT,PrimitiveType.DOUBLE]:
						raise "Shift can not be applied on float or double"
					return SGlobal.basictypes[dt1]
				else:some_method()
			elif o in [OprTernary.IF,OprTernary.ELSE]:
				if o==OprTernary.IF:
					if not SA.isBasicType(t1):raise "Expecting boolean in ternary operator"
					dt1=t1.pm_type.value
					if dt1!=PrimitiveType.BOOLEAN:raise "Expecting boolean in ternary operator"
					jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
					return t2;
				else:
					if SA.isBasicType(t1) and SA.isBasicType(t2):						
						dt1=t1.pm_type.value
						dt2=t2.pm_type.value
						if SA.isBasicNumericType(t1) and SA.isBasicNumericType(t2):
							dt=max(dt1,dt2)
							jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
							return SGlobal.basictypes[dt]
						elif dt1==PrimitiveType.BOOLEAN and dt2==PrimitiveType.BOOLEAN:
							jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
							return t1
						else:
							raise "Uncompatible datatype in ternary else"
					elif SA.isBasicType(t1) or SA.isBasicType(t2):
						#one of them is basic , and one is object
						if SA.isBasicType(t1):
							if SA.canUnbox(t2):
								ub_t2=SA.fromWrapperClassToBasic(t2)#unboxed
								dt1=t1.pm_type.value
								dt2=ub_t2.pm_type.value
								jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]+".value"
								return SGlobal.basictypes[max(dt1,dt2)]
							else:
								#This mean we have to box the basic type
								b_t1=SA.fromBasicToWrapperClass(t1)
								clz2=SA.getClassForType(t2)
								d1=b_t1.coit.clazz.getDegreeWithThis(clz2)
								d2=clz2.getDegreeWithThis(b_t1.coit.clazz)
								if d1!=-1 and d2!=-1:
									#TODO:this is modtly possible ternary else returngin same object
									if d1>d2:
										jcode[0] += SA.boxIt(t1,lcode[0]) + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
										return b_t1
									else:
										jcode[0] += SA.boxIt(t1,lcode[0]) + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
										return t2
								elif d1!=-1 or d2!=-1:
									if d1!=-1:
										jcode[0] += SA.boxIt(t1,lcode[0]) + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
										return t2
									else:
										jcode[0] += SA.boxIt(t1,lcode[0]) + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
										return b_t1
								else:
									#wrap t1
									jcode[0] += SA.boxIt(t1,lcode[0]) + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
									return SGlobal.objclass.mytype 
						else:
							#t1 is object
							if SA.canUnbox(t1):
								ub_t1=SA.fromWrapperClassToBasic(t1)#unboxed
								dt1=t2.pm_type.value
								dt1=ub_t1.pm_type.value
								jcode[0] += lcode[0]+".value" + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
								return SGlobal.basictypes[max(dt1,dt2)]
							else:
								#This mean we have to box the basic type
								b_t2=SA.fromBasicToWrapperClass(t2)
								clz1=SA.getClassForType(t1)
								d1=b_t2.coit.clazz.getDegreeWithThis(clz1)
								d2=clz1.getDegreeWithThis(b_t2.coit.clazz)
								if d1!=-1 and d2!=-1:
									#TODO:this is modtly possible ternary else returngin same object
									if d1>d2:
										jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + SA.boxIt(t2,rcode[0])
										return b_t2
									else:
										jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + SA.boxIt(t2,rcode[0])
										return t1
								elif d1!=-1 or d2!=-1:
									if d1!=-1:
										jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + SA.boxIt(t2,rcode[0])
										return t1
									else:
										jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + SA.boxIt(t2,rcode[0])
										return b_t2
								else:
									#wrap t1
									jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + SA.boxIt(t2,rcode[0])
									return SGlobal.objclass.mytype 
					else:
						clz1=SA.getClassForType(t1)
						clz2=SA.getClassForType(t2)
						d1=clz1.getDegreeWithThis(clz2)
						d2=clz2.getDegreeWithThis(clz1)
						if d1!=-1 and d2!=-1:
							#TODO:this is modtly possible ternary else returngin same object
							if d1>d2:
								jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
								return t2
							else:
								jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
								return t1
						elif d1!=-1 or d2!=-1:
							if d1!=-1:
								jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
								return t1
							else:
								jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
								return t2
						else:
							#wrap t1
							jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
							return SGlobal.objclass.mytype
				some_method()
			else:
				jcode[0] += lcode[0] + " " + SA.checkOperator(p[1].value, sym, i) + " " + rcode[0]
				return t1
			#TODO:need to do lots of checking skipping for time being
			#if o>=OprAssign.NORMAL and o<=OprAssign.RIGHT_RIGHT_SHIFT:
		else:
			raise WAFCompileError(-1, "Unkwon combination for tuple 493")
		
	@staticmethod
	def checkExpressionTupleArray(parts, sym, si ,jcode):
		#sanity check
		if len(parts)==1:
			return SCS.checkExpressionArray(parts[0],sym,si,jcode)
		if not(isinstance(parts[0],ExOperator) or isinstance(parts[1],ExOperator)):
			some_method()
		count=len(parts)
		#o1=ExOperator()
		#o2=ExOperator()
		i=0
		stack=[]
		out=[]
		p=parts		
		while i<count:
			if isinstance(p[i],ExOperator):
				o1=p[i]
				while len(stack)>0 and isinstance(stack[len(stack)-1],ExOperator):
					o2=stack[len(stack)-1]
					if o1.isLeftToRight() and o1.getPrecedance()>=o2.getPrecedance():
						out.append(stack.pop())
					elif o1.isRightToLeft() and o1.getPrecedance()>o2.getPrecedance():
						out.append(stack.pop())
					else:
						break
				stack.append(o1)
				i+=1			
			else:
				out.append(p[i])
				i+=1
		while len(stack)>0:
			out.append(stack.pop())
		
		
		count=len(out)
		out2=[]
		for i in range(count):
			out2.append(out[count-i-1])
		tc=[0] 
		r=SA.getResolvedExpression(out2,tc)
		if tc[0]!=count:
			print tc[0]
			print count
			some_method()
		return SCS.checkExpressionTuple(r, sym, si,jcode)
			
	@staticmethod
	def getResolvedExpression(a,consumed):
		count=len(a)
		if count==0:
			raise "Error" 
		o=a[0]
		tor=[]
		if not isinstance(o,ExOperator):
			tor.append(o)
			consumed[0]=1
			return tor
		if o.value in [OprPostfix.DEC,OprPostfix.INC]:
			tc=[0]
			r=SA.getResolvedExpression(a[1:],tc)
			consumed[0]=1+tc[0]
			tor.append(r)
			tor.append(o)
			return tor
		elif o.value in [OprUnary.INC,OprUnary.DEC,OprUnary.NEGATIVE,OprUnary.NOT,OprUnary.POSITIVE,OprUnary.TILDE]:
			tc=[0]
			r=SA.getResolvedExpression(a[1:],tc)
			consumed[0]=1+tc[0]
			tor.append(o)
			tor.append(r)
			return tor
		else:
			tc=[0]
			r1=SA.getResolvedExpression(a[1:],tc)
			consumed[0]=1+tc[0]
			tc=[0]
			r=SA.getResolvedExpression(a[consumed[0]:],tc)
			consumed[0]+=tc[0]
			tor.append(r)
			tor.append(o)
			tor.append(r1)
			
			return tor

	@staticmethod
	def checkExpressionArray(parts, sym, i, jcode):
		if len(jcode) == 0:jcode.append("")
		if isinstance(parts, ExType):
			if parts.typ.coit != None:
				jcode[0] += parts.typ.coit.clazz.getPrototype()
			SHelper.processType(parts.typ, SCS.currentClass, SCS.currentMethod)
			return parts.typ
		if not isinstance(parts, list):			 
			some_method()
			return
		#print "Parts " + SA.toSParts(parts)
		if SA.isExpressionTuple(parts):
			return SCS.checkExpressionTuple(parts, sym, i, jcode)
		pcount = len(parts)
		for pi in range(0, pcount):
			p = parts[pi]
			if isinstance(p, ExPrimary):
				#it can be followeb by selector and postfix operators ++,--
				r = SCS.checkExpressionArray(p.parts, sym, i, jcode)
				if pi + 1 == pcount:return r
				np = parts[pi + 1]
				if isinstance(np, ExDot):
					jcode[0] += "."
					return SCS.checkDotDotExpression(r, parts, pi + 2, pcount, sym, i, jcode)
				###########
				if isinstance(np, ExArrayIndex):
					return SCS.checkDotDotExpression(r, parts, pi + 1, pcount, sym, i, jcode)
					"""
					if r.coit == None or r.coit.clazz != SGlobal.arrayclass:
						raise WAFCompileError(-1, "Not an array")
					code = []
					t = SCS.checkExpression(np.exp, sym, i, code)
					jcode[0] += "[" + code[0] + "]"
					if isinstance(t, Type):
						if not SA.canBeArrayIndex(t):
							raise WAFCompileError("Can not evalute to positive integer")
					if pi + 2 == pcount:return SA.getTypeWithReducedArray(r)
					code = []
					r = SCS.checkDotDotExpression(SA.getTypeWithReducedArray(r), parts, pi + 2, pcount, sym, i, code)
					jcode[0] += code[0]
					return r
					"""
				###########
				raise WAFCompileError(-1, "Primary Error 535")
				#TODO:handle postfix operators ++,--

			elif isinstance(p, list):
				#if SA.isExpressionTuple(p):
				#		return SA.checkExpressionTuple(p, sym, i,jcode)
				#else:
				return SCS.checkExpressionTupleArray(parts, sym, i, jcode)
			elif isinstance(p, ExThis):
				jcode[0] += "this"
				if pi + 1 == pcount:
					return SCS.currentClass.mytype
				np = parts[pi + 1]
				#this()

				if isinstance(np, ExArguments):#calling another constructor
					code = []
					argstl = SCS.getExpressionListToTypeList(np.arguments, sym, i, code)
					_argstl = []
					for _arg in argstl: 
						_argstl.append(SCS.currentClass.mytype.mapAndConvertType(_arg,None,SCS.currentMethod))
					argstl = _argstl
					cc = SCS.currentClass.getConstructor(argstl, SCS.currentClass)
					if  cc == None:
						raise WAFCompileError(1007, SCS.currentClass.name)
					#TODO:J call another constructor here .. written below check this
					SA.applyJSTypeCastForArguments(cc, argstl, code)
					jcode[0] += "." + cc.getJSName() + "(" + ",".join(code) + ")"
					
					pi = pi + 1
				#this.member....
				elif isinstance(np, ExDot):
					pi = pi + 2
					p = parts[pi]
					jcode[0] += "."
					if pi + 1 == pcount:
						f = SCS.currentClass.getFieldWithThisAccess(p.name.data, False, SCS.currentClass)
						if f == None:raise WAFCompileError(1008, p.name)
						jcode[0] += f.field.getJSName()
						return SCS.currentClass.mytype.mapAndConvertType(f.type,None,SCS.currentMethod)
					np = parts[pi + 1]
					if isinstance(np, ExDot):
						f = SCS.currentClass.getFieldWithThisAccess(p.name.data, False, SCS.currentClass)
						if f == None:raise WAFCompileError(1008, p.name)
						jcode[0] += f.field.getJSName()
						jcode[0] += "."
						r = SCS.currentClass.mytype.mapAndConvertType(f.type,None,SCS.currentMethod)
						return SCS.checkDotDotExpression(r, parts, pi + 2, pcount, sym, i, jcode)
					elif isinstance(np, ExArguments):
						#########
						args = np.arguments
						curType=SCS.currentClass.mytype
						if curType.coit.clazz.package=="com.openwaf.client.dom" and WAFConfig.isCompatibleWithIE67():
							args = np.arguments
							code = []
							argstl = SCS.getExpressionListToTypeList(args, sym, i, code)
							#mapping not required
							cc=curType.coit.clazz
							m = curType.getMethodWithThisAccess(p.name.data, argstl, False,None, SCS.currentClass)
							if m==None:
								raise Exception("Method not found "+p.name.data)
							SA.applyJSTypeCastForArguments(m, argstl, code)
							if m.method.method.block == None and m.method.method.native_code == None:
								#can not minify this
								jcode[0]+=m.method.getJSName()+"("+",".join(code)+")"								
								r = m.rtype
								if m.method.is_void:return None
								if pi + 2 == pcount:return r
								if not isinstance(parts[pi + 2], ExDot):raise WAFCompileError(0, "what is this in method")
								jcode[0] += "."
								return SCS.checkDotDotExpression(r, parts, pi + 3, pcount, sym, i, jcode)
							else:
								if len(jcode[0])>0 and jcode[0][-1]==".":jcode[0]=jcode[0][:-1]
								line=None
								line=cc.getPrototype()+".prototype."+m.method.getJSName()+".call("
								if len(code)>0:
									jcode[0]=line+jcode[0]+","+",".join(code)+")"
								else:
									jcode[0]=line+jcode[0]+")"
								r = m.rtype
								if m.method.is_void:return None
								if pi + 2 == pcount:return r
								if not isinstance(parts[pi + 2], ExDot):raise WAFCompileError(0, "what is this in method")
								jcode[0] += "."
								return SCS.checkDotDotExpression(r, parts, pi + 3, pcount, sym, i, jcode)
						
						#########
						args = np.arguments
						code = []
						argstl = SCS.getExpressionListToTypeList(args, sym, i, code)
						_argstl = []
						for _arg in argstl: 
							_argstl.append(SCS.currentClass.mytype.mapAndConvertType(_arg,None,SCS.currentMethod))
						argstl = _argstl
						#access_control=SA.getAccessControl(SCS.currentClass,SCS.currentClass)
						m = SCS.currentClass.mytype.getMethodWithThisAccess(p.name.data, argstl, False, None,SCS.currentClass)
						if m==None:
							raise Exception("Method not found "+p.name.data)						
						SA.applyJSTypeCastForArguments(m, argstl, code)
						if m.method.calls_model==True:
							if m.method.isAbstract():
								if WAFConfig.isMinify() == False:
									SCS.s_model_call="this."+m.method.getName()+"_" + str(m.method.mid) + "(" + ",".join(code)
									SCS.s_model_call2="this."+m.method.getName()+"_" + str(m.method.mid) + "("  
								else:
									SCS.s_model_call="this."+"_" + str(m.method.mid) + "(" + ",".join(code)
									SCS.s_model_call2="this."+"_" + str(m.method.mid) + "(" 
							else:
								SCS.s_model_call="this."+m.method.getJSName() + "(" + ",".join(code)
								SCS.s_model_call2="this."+m.method.getJSName() + "("
							SCS.direct_model_call=False
							if len(code)>0:
								SCS.s_model_call+=",_g,_f+1);"
								args=[]
								for i in code:
									args.append("0")
								SCS.s_model_call2+=(",".join(args))+",_g,_f+1);"
							else:
								SCS.s_model_call+="_g,_f+1);"
								SCS.s_model_call2+="_g,_f+1);"
							if m.rtype!=None:
								jcode[0] +=  SCS.s_temp_name
							else:
								jcode[0]=""
						else:
							if m.method.isAbstract():
								if WAFConfig.isMinify() == False:
									jcode[0] +=  m.method.getName()+"_" + str(m.method.mid) + "(" + ",".join(code) + ")"
								else:
									jcode[0] +=  "_" + str(m.method.mid) + "(" + ",".join(code) + ")"
							else:
								jcode[0] += m.method.getJSName() + "(" + ",".join(code) + ")"
						#m = SCS.currentClass.getMethodPrivateAccess(p.name.data, argstl, 0)
						if m == None:
							raise WAFCompileError(1009, p.name.data)
						if m.method.is_void:return None
						r = SCS.currentClass.mytype.mapAndConvertType(m.rtype,None,SCS.currentMethod)
						if pi + 2 == pcount:return r
						if not isinstance(parts[pi + 2], ExDot):raise WAFCompileError(0, "what is this in method")
						jcode[0] += "."
						return SCS.checkDotDotExpression(r, parts, pi + 3, pcount, sym, i, jcode)
					else:
						raise WAFCompileError(-1, "What the hell is this")
				else:
					raise WAFCompileError(-1, "What the hell is this")
			elif isinstance(p, ExIdentifier):
				name = p.name.data;
				if pi + 1 == pcount:
					t = SA.getVariable(name, sym, i)
					#if  SA.isDeclaration(t):
					#	jcode[0] += t.getPrototype()
					#	return t
					if t == None:
						t = SA.getFieldFromCurrentClass(name)#update this for static members
						if t != None:
							if t.field.isStatic():
								jcode[0] += t.field.getDeclaringClass().getPrototype() + ".prototype." + t.field.getJSName()
							else:
								jcode[0] += "this." + t.field.getJSName()
						else:
							t = SA.getFieldFromContainerClass(name)
							if t == None:
								print p.name 
								raise WAFCompileError(1009, p.name)
							if t.field.isStatic():
								jcode[0] += t.field.getDeclaringClass().getPrototype() + ".prototype." + t.field.getJSName()
							else:
								d = SCS.currentClass.getDepthRelativeToThis(t.field.clazz)
								jcode[0] += "this" + ("._pi" * d) + "." + t.field.getJSName()
							#TODO:adjust code to acces if from parent class
					else:
						if isinstance(t, SEnum):
							jcode[0] +=name
						else:
							jcode[0] += t.getJSName()
					t=SA.getTypeOfVariable(t)
					if t == None:
						raise WAFCompileError(1009, p.name)
					#TODO:could be a problem as javascript is getting added two times (on 4 lines backword)
					if  SA.isDeclaration(t):
						jcode[0] += t.getPrototype()
						return t
					return SCS.currentClass.mapAndConvertType(SA.getTypeOfVariable(t), None, SCS.currentClass,None,SCS.currentMethod)#TODO:this is wrong i guess
				np = parts[pi + 1]
				if isinstance(np, ExDot) or isinstance(np, ExArrayIndex):
					t = SA.getVariable(name, sym, i)
					if t != None and isinstance(t, SPackage):
						npi = pi + 1
						pack_str = t.name 
						while  npi + 1 < pcount and isinstance(parts[npi], ExDot) and  isinstance(parts[npi + 1], ExIdentifier):
							p = parts[npi + 1]
							t = SA.getVariable(pack_str + "." + p.name.data, sym, i)
							npi += 2
							if isinstance(t, SPackage):
								pack_str += "." + p.name.data
							elif isinstance(t, STypeDeclaration):
								pack_str += "." + p.name.data
								break
							else:
								print t, pack_str + "." + p.name.data
								print "Error", some_method()
						if not isinstance(t, STypeDeclaration):
							print "Type not found", pack_str
							some_method()
						if npi + 1 == pcount:
							jcode[0] += t.getPrototype()
							return t
						np = parts[npi]
						if not isinstance(np, ExDot):
							print "Expecting dot(.)", some_method()
						npi = npi + 1
						if npi + 1 > pcount :
							print "Unexpected ", some_method()#TODO:ERROR REPORT
						np = parts[npi]
						if isinstance(np, ExThis):
							#depth goes her in java2js
							d = SCS.currentClass.getDepthRelativeToThis(t)
							jcode[0] += "this" + ("._pi" * d)
							if npi + 1 == pcount:
								return t.mytype
							else:
								return SCS.checkDotDotExpression(t.mytype, parts, npi + 1, pcount, sym, i, jcode)
						else:
							jcode[0] += t.getPrototype() + ".prototype."
							return SCS.checkDotDotExpression(t, parts, npi, pcount, sym, i, jcode)
					if t != None and isinstance(t, STypeDeclaration):
						npi = pi + 1
						pack_str = t.name 
						cur_class = t
						while  npi + 1 < pcount and isinstance(parts[npi], ExDot) and  isinstance(parts[npi + 1], ExIdentifier):
							p = parts[npi + 1]
							t = cur_class.getInnerMember(p.name.data)
							if t == None:
								if cur_class.getDegreeWithThis(SGlobal.wafmodel)>=0:
									SCS.calls_model=True									
								else:
									jcode[0] += cur_class.getPrototype() + ".prototype."
								return SCS.checkDotDotExpression(cur_class, parts, npi + 1, pcount, sym, i, jcode)
							cur_class = t
							npi += 2
						t = cur_class
						if not isinstance(cur_class, STypeDeclaration):
							print "Type not found", pack_str
							some_method()
						if npi + 1 == pcount:
							jcode[0] += t.getPrototype()
							return t
						np = parts[npi]
						if not isinstance(np, ExDot):
							print "Expecting dot(.)", some_method()
						npi = npi + 1
						if npi + 1 > pcount :
							print "Unexpected ", some_method()#TODO:ERROR REPORT
						np = parts[npi]
						if isinstance(np, ExThis):
							#depth goes her in java2js
							d = SCS.currentClass.getDepthRelativeToThis(t)
							jcode[0] += "this" + ("._pi" * d)
							if npi + 1 == pcount:
								return t.mytype
							else:
								return SCS.checkDotDotExpression(t.mytype, parts, npi + 1, pcount, sym, i, jcode)
						else:
							jcode[0] += t.getPrototype() + ".prototype."
							return SCS.checkDotDotExpression(t, parts, npi, pcount, sym, i, jcode)
							
							
								
							
							
							
					#if SA.isDeclaration(t):
					#	jcode[0] += t.getPrototype() + ".prototype."
					#	return SA.checkDotDotExpression(t, parts, pi + 2, pcount, sym, i, jcode)
					if t == None:
						t = SA.getFieldFromCurrentClass(name)#update this for static members
						if t != None:
							if t.field.isStatic():
								jcode[0] += t.field.getDeclaringClass().getPrototype() + ".prototype." + t.field.getJSName()
							else:
								jcode[0] += "this." + t.field.getJSName()
						else:
							t = SA.getFieldFromContainerClass(name)#TODO:update from
							if t == None:
								raise WAFCompileError(1009, p.name)
							if t.field.isStatic():
								jcode[0] += t.field.getDeclaringClass().getPrototype() + ".prototype." + t.field.getJSName()
							else:
								d = SCS.currentClass.getDepthRelativeToThis(t.field.clazz)
								jcode[0] += "this" + ("._pi" * d) + "." + t.field.getJSName()
						
					else:
						jcode[0] += t.getJSName()
					t=SA.getTypeOfVariable(t)
					if t == None:
						print name
						raise WAFCompileError(1009, p.name)
					vtype = vtype = SCS.currentClass.mapAndConvertType(SA.getTypeOfVariable(t), None, SCS.currentClass,None,SCS.currentMethod)
					if isinstance(np, ExDot):
						
						jcode[0] += "."
						if vtype.coit != None:#coit type
							return SCS.checkDotDotExpression(vtype, parts, pi + 2, pcount, sym, i, jcode)
						print "VN", name, SA.ttos(np)
						raise WAFCompileError(-1, "Expecting class,interface , enum ,obejct")
					elif isinstance(np, ExArrayIndex):
						if vtype.coit == None or vtype.coit.clazz != SGlobal.arrayclass:
							raise WAFCompileError(-1, "Not an array")
						code = []
						t = SCS.checkExpression(np.exp, sym, i, code)
						if not SA.canBeArrayIndex(t):
							raise WAFCompileError("Can not evalute to positive integer")
						jcode[0] += "[" + code[0] + "]"
						if pi + 2 == pcount:return SA.getTypeWithReducedArray(vtype)
						#TODO:Might need an update here
						return SCS.checkDotDotExpression(SA.getTypeWithReducedArray(vtype), parts, pi + 2, pcount, sym, i, jcode)
				elif isinstance(np, ExArguments):
					curClass = SCS.currentClass
					#### IE 6
					curType=curClass.mytype
					if curType.coit.clazz.package=="com.openwaf.client.dom" and WAFConfig.isCompatibleWithIE67():
						args = np.arguments
						code = []
						argstl = SCS.getExpressionListToTypeList(args, sym, i, code)
						#mapping not required
						cc=curType.coit.clazz
						m = curType.getMethodWithThisAccess(name, argstl, False,None, SCS.currentClass)
						if m!=None:
							SA.applyJSTypeCastForArguments(m, argstl, code)						
							if m.method.method.block == None and m.method.method.native_code == None:
								#can not minify this
								jcode[0]+="this."+m.method.getJSName()+"("+",".join(code)+")"								
								if m.method.is_void == True:return None
								rtype = m.rtype
								if pi + 2 == pcount:return rtype
								return SCS.checkDotDotExpression(rtype, parts, pi + 2, pcount, sym, i, jcode)					
							else:
								if len(jcode[0])>0 and jcode[0][-1]==".":jcode[0]=jcode[0][:-1]
								line=None
								line=cc.getPrototype()+".prototype."+m.method.getJSName()+".call(this"
								if len(code)>0:
									jcode[0]=line+jcode[0]+","+",".join(code)+")"
								else:
									jcode[0]=line+jcode[0]+")"
						
								if m.method.is_void == True:return None
								rtype = m.rtype
								if pi + 2 == pcount:return rtype
								return SCS.checkDotDotExpression(rtype, parts, pi + 2, pcount, sym, i, jcode)
						m = curClass.getMethodFromContainerClass(name, argstl, False, SCS.currentClass)
						if m==None:
							print "Method not found ",name
							some_method()
						SA.applyJSTypeCastForArguments(m, argstl, code)
						dclazz=m.method.clazz
						d = cc.getDepthRelativeToThis(dclazz)
						if d<0: some_method()
						if m.method.method.block == None and m.method.method.native_code == None:
							#TODO:not sure about this what exactly is this
							jcode[0]+="this"+("._pi" * d)+m.method.getJSName()+"("+",".join(code)+")"								
							if m.method.is_void == True:return None
							rtype = m.rtype
							if pi + 2 == pcount:return rtype
							return SCS.checkDotDotExpression(rtype, parts, pi + 2, pcount, sym, i, jcode)					
						else:
							if len(jcode[0])>0 and jcode[0][-1]==".":jcode[0]=jcode[0][:-1]
							line=None
							line=dclazz.getPrototype()+".prototype."+m.method.getJSName()+".call(this"+("._pi" * d)
							if len(code)>0:
								jcode[0]=line+jcode[0]+","+",".join(code)+")"
							else:
								jcode[0]=line+jcode[0]+")"
					
							if m.method.is_void == True:return None
							rtype = m.rtype
							if pi + 2 == pcount:return rtype
							return SCS.checkDotDotExpression(rtype, parts, pi + 2, pcount, sym, i, jcode)
					###### IE 6
					code = []
					argstl = SCS.getExpressionListToTypeList(np.arguments, sym, i, code)
					_argstl = []
					for _arg in argstl: 
						_argstl.append(curClass.mytype.mapAndConvertType(_arg,None,SCS.currentMethod))
					argstl = _argstl
					m = curClass.mytype.getMethodWithThisAccess(name, argstl, False,None, SCS.currentClass)
					if m != None:
						#SA.applyJSTypeCastForArguments(m, argstl, code)
						if m.method.isStatic():
							jcode[0] += m.method.getDeclaringClass().getPrototype() + ".prototype" 
						else:
							jcode[0] += "this"
					else:
						m = curClass.getMethodFromContainerClass(name, argstl, False, SCS.currentClass)
						if m == None:
							print p.name.lineno, p.name.pos
							print "SA ", SCS.currentClass.fullname
							print "curClass", curClass.fullname, curClass.exclass[0].fullname, name
							raise WAFCompileError(1009, p.name)
						#SA.applyJSTypeCastForArguments(m, argstl, code)
						if m.method.isStatic():
							jcode[0] += m.method.getDeclaringClass().getPrototype() + ".prototype"
						else:
							d = SCS.currentClass.getDepthRelativeToThis(m.method.clazz)
							jcode[0] += "this" + ("._pi" * d)
					#TODO:J update this based on in which ckass we fint method hint pcl-pc-1
					#jcode[0]+="this."+m.getJSName()+"("+code[0]+")"
					SA.applyJSTypeCastForArguments(m, argstl, code)
					if m.method.calls_model==True:
						d = SCS.currentClass.getDepthRelativeToThis(m.method.clazz)
						if m.method.isAbstract():
							if WAFConfig.isMinify() == False:
								SCS.s_model_call="this"+ ("._pi" * d)+"."+m.method.getName()+"_" + str(m.method.mid) + "(" + ",".join(code)
								SCS.s_model_call2="this"+ ("._pi" * d)+"."+m.method.getName()+"_" + str(m.method.mid) + "("  
							else:
								SCS.s_model_call="this"+ ("._pi" * d)+"."+"_" + str(m.method.mid) + "(" + ",".join(code)
								SCS.s_model_call2="this"+ ("._pi" * d)+"."+"_" + str(m.method.mid) + "(" 
						else:
							SCS.s_model_call= "this"+ ("._pi" * d)+"."+m.method.getJSName() + "(" + ",".join(code)
							SCS.s_model_call2= "this"+ ("._pi" * d)+"."+m.method.getJSName() + "("
						SCS.direct_model_call=False
						if len(code)>0:
							SCS.s_model_call+=",_g,_f+1);"
							args=[]
							for i in code:
								args.append("0")
							SCS.s_model_call2+=(",".join(args))+",_g,_f+1);"
						else:
							SCS.s_model_call+="_g,_f+1);"
							SCS.s_model_call2+="_g,_f+1);"
						if m.rtype!=None:
							jcode[0] +=  SCS.s_temp_name
						else:
							jcode[0]="";
					else:
						if m.method.isAbstract():
							if WAFConfig.isMinify() == False:
								jcode[0] += "." + m.method.getName()+"_" + str(m.method.mid) + "(" + ",".join(code) + ")"
							else:
								jcode[0] += "." +"_" + str(m.method.mid) + "(" + ",".join(code) + ")"
								
						else:
							jcode[0] += "." + m.method.getJSName() + "(" + ",".join(code) + ")"
					if m.method.is_void == True:return None
					rtype = curClass.mytype.mapAndConvertType(m.rtype,None,SCS.currentMethod)
					if pi + 2 == pcount:return rtype
					return SCS.checkDotDotExpression(rtype, parts, pi + 2, pcount, sym, i, jcode)
				elif isinstance(np, ExInnerCreator):
					curClass = SCS.currentClass
					t = SA.getVariable(name, sym, i)
					creator = np.creator
					if t != None:
						jcode[0] += t.getJSName()
					if t == None:
						t = SA.getFieldFromCurrentClass(name)#update this for static members
						if t.field.isStatic():
							jcode[0] += t.field.getDeclaringClass().getPrototype() + ".prototype." + t.field.getJSName()
						else:
							jcode[0] += "this." + t.field.getJSName()
					if t == None:
						t = SA.getFieldFromContainerClass(name)
						if t == None:
							raise WAFCompileError(1009, p.name)
						if t.field.isStatic():
							jcode[0] += t.field.getDeclaringClass().getPrototype() + ".prototype." + t.field.getJSName()
						else:
							d = SCS.currentClass.getDepthRelativeToThis(t.field.clazz)
							jcode[0] += "this" + ("._pi" * d) + "." + t.field.getJSName()
					t=SA.getTypeOfVariable(t)
					outerClass = SA.getTypeOfVariable(t).coit.clazz
					innerClass = outerClass.getInnerMember(creator.name.data)
					acode = []
					argstl = SCS.getExpressionListToTypeList(creator.classcreator.args, sym, i, acode)		
					_argstl = []
					for _arg in argstl: 
						_argstl.append(curClass.mytype.mapAndConvertType(_arg,None,SCS.currentMethod))
					argstl = _argstl
					cons = innerClass.getConstructor(argstl, SCS.currentClass)
					if cons == None:
						print "Constructor not found for inner class"
						print innerClass.getFullname()
						print outerClass.getFullname()
						some_method()
					line = None
					#if cons.isDefaultConstructor():
					#	line = "new " + innerClass.getPrototype() + "()"
					#else:
					line = "(new " + innerClass.getPrototype() + "())." + cons.getJSName() + "(" + ",".join(acode) + ")"
					jcode[0] += "._ic(" + line + ")"
					return innerClass.mytype
				else:
					print "Not handled"
					some_method()
			
			elif isinstance(p, ExCastExpression):
				#TODO:it me array be carefull not handled right now
				#TODO:check compile time for possible casting of this
				#TODO:J check this
				
				t = SCS.checkExpressionArray(p.exp, sym, i, jcode)
				if isinstance(p.typ, PrimitiveType):
					tc=SHelper.getClassOnFullName("com.openwaf.core.framework.TypeCast")
					v=p.typ.value
					if v==PrimitiveType.BYTE:
						jcode[0]=tc.getPrototype()+".prototype.rb("+jcode[0]+")"
					if v==PrimitiveType.CHAR:
						jcode[0]=tc.getPrototype()+".prototype.rc("+jcode[0]+")"
					if v==PrimitiveType.INT:
						jcode[0]=tc.getPrototype()+".prototype.ri("+jcode[0]+")"
					if v==PrimitiveType.SHORT:
						jcode[0]=tc.getPrototype()+".prototype.rs("+jcode[0]+")"	
					return SGlobal.getBasicTypeForPrimitiveType(p.typ)
				else:
					SHelper.processType(p.typ, SCS.currentClass, SCS.currentMethod)
					return SCS.currentClass.mytype.mapAndConvertType(p.typ,None,SCS.currentMethod)

			elif isinstance(p, ExCreator):
				## class creator
				#TODO:J handle this
				c = p.creator
				if c.arraycreator == None:
					code = []
					if SCS.currentMethod==None:
						r = SA.processClassCreator(c, sym, i, code,True)
					else:
						r = SA.processClassCreator(c, sym, i, code,False)
					jcode[0] += code[0]
					return r
				else:
					ac = c.arraycreator
					if ac.init == None:
						code = []
						r = SA.processArrayCreator(c.arraycreator, sym, i, code)
						jcode[0] += WAFConfig.getWAFRootObjectName() + ".createArray(" + code[0] + ")"
						return r
					else:
						code = []
						r = SA.processArrayCreator2(c.arraycreator, sym, i, code)
						jcode[0] += code[0]
						return r
			elif isinstance(p, ExLiteral):
				return SA.checkLiteral(p.literal, sym, i, jcode)
			elif isinstance(p, ExParExpression):
				code = []
				r = SCS.checkExpression(p.exp, sym, i, code)
				jcode[0] += "(" + code[0] + ")"
				return r
			elif isinstance(p, ExPrimitiveType):
				#TODO:verify this currently ignoring
				#TODO:J check this
				return SGlobal.getBasicTypeForPrimitiveType(p)

			elif isinstance(p, ExSuper):
				#TODO:we need to handle array index here in ExThis is Semantic.py as well
				
				if len(SCS.currentClass.exclass) == 0:
					raise WAFCompileError("Class dosent have super class")

				supClass = SCS.currentClass.exclass[0]
				np = parts[pi + 1]
				if isinstance(np, ExArguments):#calling super constructor
					jcode[0] += "this"#TODO:i am sure about this
					code = []
					argstl=SCS.getExpressionListToTypeList(np.arguments, sym, i, code)
					sc = supClass.getConstructor(argstl, SCS.currentClass)
					if sc == None:
						raise WAFCompileError(1007, None)
					SA.applyJSTypeCastForArguments(sc, argstl, code)
					jcode[0] += "." + sc.getJSName() + "(" + ",".join(code) + ")"
					pi = pi + 1
					return None
				#this.member....
				elif isinstance(np, ExDot):
					pi = pi + 2
					p = parts[pi]
				
					if pi + 1 == pcount:
						jcode[0] += "this."#TODO:i am sure about this
						f = supClass.getFieldWithThisAccess(p.name.data, False, SCS.currentClass)
						if f == None:raise WAFCompileError(1008, p.name)
						jcode[0] += f.field.getJSName()
						return SCS.currentClass.mytype.mapAndConvertType(f.type,None,SCS.currentMethod)
					np = parts[pi + 1]
					if isinstance(np, ExDot):
						jcode[0] += "this."#TODO:i am sure about this
						f = supClass.getFieldWithThisAccess(p.name.data, False, SCS.currentClass)
						if f == None:raise WAFCompileError(1008, p.name)
						jcode[0] += f.field.getJSName()
						r = SCS.currentClass.mytype.mapAndConvertType(f.type,None,SCS.currentMethod)
						return SCS.checkDotDotExpression(r, parts, pi + 2, pcount, sym, i, jcode)
					elif isinstance(np, ExArguments):
						jcode[0] += supClass.getPrototype()+".prototype."
						args = np.arguments
						code = []
						argstl = SCS.getExpressionListToTypeList(args, sym, i, code)
						_argstl = []
						for _arg in argstl: 
							_argstl.append(SCS.currentClass.mytype.mapAndConvertType(_arg,None,SCS.currentMethod))
						argstl = _argstl
						m = supClass.getMethodWithThisAccess(p.name.data, argstl, False,None, SCS.currentClass)
						if m == None:
							raise WAFCompileError(1009, p.name.data)
						SA.applyJSTypeCastForArguments(m, argstl, code)
						if m.method.isAbstract():
							if WAFConfig.isMinify() == False:
								jcode[0] +=  m.method.getName()+"_" + str(m.method.mid) + ".call(this," + ",".join(code) + ")"
							else:
								jcode[0] +=  "_" + str(m.method.mid) + ".call(this" + ",".join(code) + ")"
						else:
							if len(code) > 0:
								jcode[0] += m.method.getJSName() + ".call(this," + ",".join(code) + ")"
							else:
								jcode[0] += m.method.getJSName() + ".call(this)"
						if m.method.is_void:return None
						r = SCS.currentClass.mytype.mapAndConvertType(m.rtype,None,SCS.currentMethod)
						if pi + 2 == pcount:return r
						if isinstance(parts[pi + 2], ExDot):
							jcode[0] += "."
							return SCS.checkDotDotExpression(r, parts, pi + 3, pcount, sym, i, jcode)
						if isinstance(parts[pi + 2], ExArrayIndex):
							return SCS.checkDotDotExpression(r, parts, pi + 2, pcount, sym, i, jcode)
						raise WAFCompileError(0, "what is this in method")
				else:
					raise WAFCompileError(-1, "What the hell is this")
					#TODO:
					print "Super not supported"
					some_method()
					return None
					
			else:
				print "UnExpected:Unknown Expression part ", p
				some_method()
			pi += 1
		return None#TODO:could be error
	@staticmethod
	def processArrayCreator(ac, sym, i, jcode):
		#TODO:process array creator init
		#TODO:j
		line = "["
		add_comm = False
		if ac.exps != None:
			#if ac.arraydim != len(ac.exps):
			#	print "Array initialization not supported"
				##some_method()
			for e in ac.exps:
				if add_comm:line += ","
				code = []
				SCS.checkExpression(e, sym, i, code)
				line += "".join(code)
				add_comm = True
		line += "]"
		jcode.append(line)
		t = Type()
		t.arraydim = ac.arraydim

		if isinstance(ac.name, ClassOrInterfaceType):
			t.coit = ac.name
		else:
			t.pm_type = ac.name
		SHelper.processType(t, SCS.currentClass, SCS.currentMethod)
		return t
	@staticmethod
	def processArrayCreator2(ac, sym, i, jcode):
		#TODO:process array creator init
		#TODO:j
		code = []
		SCS.checkArrayInitializer(ac.init, sym, i, code)
		jcode.append("".join(code))
		t = Type()
		t.arraydim = ac.arraydim

		if isinstance(ac.name, ClassOrInterfaceType):
			t.coit = ac.name
		else:
			t.pm_type = ac.name
		SHelper.processType(t, SCS.currentClass, SCS.currentMethod)
		return t
	@staticmethod
	def checkArrayInitializer(ai, sym, i, jcode):
		line = "["
		add_comma = False
		for vi in ai.part:
			if add_comma == True:line += ","
			code = []
			SCS.checkVariableInitializer(vi, sym, i, code)
			line += code[0]
			add_comma = True
		line += "]"
		jcode.append(line)
	
